【问题标题】:click event does not fire on newly created li tagsclick 事件不会在新创建的 li 标签上触发
【发布时间】:2013-11-20 04:59:50
【问题描述】:

使用以下代码:

<!DOCTYPE html>
<html>
<head>
<title>test list</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<style>
li{
display:inline;
}
</style>
<body>
<input type="hidden" value="4" id="value">

<ol></ol>

<button id="btn2">increase</button>
<button id="btn1">show</button>
<p></p>
</body>
<script>
$("li").click(function(){
    $(this).nextAll().css({"color":"red"});;
});

$("#btn2").click(function(){
    var text="<li> -> kkk</li>"; 
    $("ol").append(text);
});

$("#btn1").click(function(){
    $("p").text($("li").length);
});
</script>
</html>

点击“增加”按钮后出现的任何新创建的“li”标签,不会触发绑定到点击事件的处理程序。

$("li").click(function(){
    $(this).nextAll().css({"color":"red"});;
});

你能告诉我它不起作用的原因吗?有没有可能让它发挥作用?如果是,如何?非常感谢。

【问题讨论】:

    标签: javascript jquery html event-delegation


    【解决方案1】:

    试试这样:因为你的 'li' 是动态生成的 (For further reading)

    $("body").on('click','li',function(){
        $(this).nextAll().css({"color":"red"});;
    });
    

    【讨论】:

      【解决方案2】:

      来自 jQuery 文档:“事件处理程序仅绑定到当前选定的元素;它们必须在您的代码调用 .on() 时存在于页面上。为了确保元素存在并且可以被选择,为页面上 HTML 标记中的元素在文档就绪处理程序中执行事件绑定。如果将新 HTML 注入页面,请在将新 HTML 放入页面后选择元素并附加事件处理程序。或者,使用委托事件以附加事件处理程序,如下所述。"

      【讨论】:

        【解决方案3】:

        试试这个代码:

           $(document).on('click', 'li', function(){
        
                $(this).nextAll().css({"color":"red"});;
           });
        

        【讨论】:

          【解决方案4】:

          可能有助于将您的脚本库放在结束正文标记之前 ...

            增加 显示

            ... 见这里:fiddle link
            $(function() {  
            $("#btn2").click(function(){  
                var text= " --> ";  
                $('ol').append('<li>'+text+'</li>');  
                $('ol li:not(":first")').css('color','red');  
            });  
            
            $("#btn1").click(function(){  
                $("p").text($("li").length);  
            });     
            });  
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2014-01-08
              • 1970-01-01
              • 2012-10-10
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-02-21
              • 2010-10-19
              相关资源
              最近更新 更多