点击事件不会触发新创建的li标签

时间:2013-11-20 04:59:51

标签: javascript jquery html event-delegation

使用以下代码:

<!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"});;
});
你可以告诉我它不起作用的原因。是否可以使它工作?如果是,怎么样?非常感谢你。

4 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

试试这段代码:

   $(document).on('click', 'li', function(){

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

答案 3 :(得分:0)

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

    增加     节目     

              ... 见这里: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);  
});     
});  
相关问题