JS动态为UL创建1个LI 为LI绑定一个Onlick事件。怎么做?

解决方案 »

  1.   


    <!doctype html>
    <html>
    <head>
    <meta charset="gb2312" />
    <title></title>
    <style>
    </style>

    </head>
    <body>
    <ul id="test">
    </ul>
    <script>
    function $(o){return document.getElementById(o)}
    var li = document.createElement('li');
    li.innerHTML = 123;
    li.onclick = function(){
    alert(123)
    }
    $('test').insertBefore(li, $('test').firstChild)
    </script>
    </body>
    </html>
      

  2.   

    注意insertBefore的兼容性
    用appendChild
      

  3.   


    up~`用 $('test').appendChild(li)
      

  4.   

    请说说在什么情况下 不兼容了?我测试了的,ie ff下都没问题。
      

  5.   

    用 JQuery 对li 标签添加Mousedown事件,xxx 表示li的class值,供参考$(document).ready(function() {
        $("li.xxx").each(function() {
            if (!$.data(this, 'events') || $.data(this, 'events').mousedown === undefined) {
                $(this).mousedown(function() {
                    //do something
                });
            }
        });
      

  6.   

     $(function(){
        $("ul>li").bind({
           click:function(){
               if($(this).hasClass("red")){
                  $(this).removeClass("red").addClass("blue");
               }else{
                  $(this).removeClass("blue").addClass("red");
               }  
            }
        });
     });动态给li绑定click事件,点击li进行class的red,blue变换,参考下吧