With the following code:
<!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>
any newly created "li" tags that appear after clicking "increase" button, do not trigger handlers bound to the click event.
$("li").click(function(){
$(this).nextAll().css({"color":"red"});;
});
Can you please tell me the reason why it's not work. And is it possible to make it work? If yes, How? Thank you very much.
Try like this : As your 'li' are generating dynamically ( For further reading )
$("body").on('click','li',function(){
$(this).nextAll().css({"color":"red"});;
});
从jQuery文档中:“事件处理程序仅绑定到当前选择的元素;在代码调用.on()时,它们必须存在于页面上。要确保这些元素存在并且可以被选择,请执行事件绑定在文档就绪处理程序中,用于页面HTML标记中的元素。如果将新HTML注入页面,请选择元素并在将新HTML放入页面后附加事件处理程序;或者使用委托事件来处理附加一个事件处理程序,如下所述。”
try this code:
$(document).on('click', 'li', function(){
$(this).nextAll().css({"color":"red"});;
});
May help to put your script library before the closing body tag ...
$(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); }); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.