Jquery事件不适用于动态附加元素
我试图将新的DOM对象附加到某个Div并且它可以工作,但不知何故 – 我为这些新附加对象编写的事件没有响应。 这是为什么?
我在这里附上一个简单的例子:点击段落应该隐藏的任何段落。 然而,对于使用.append添加的段落,它不起作用。
http://jsfiddle.net/xV3HN/
有我的代码:
$(document).ready(function(){ $("#add").click(function(){ $("#containerDiv").append(" I should hide as well if you click me
"); }); $("p").click(function(){ $(this).hide(); }); });
您需要使用.on
来处理动态元素的事件。
试试这个:
$(document).on('click', 'p', function(){ $(this).hide(); });
DEMO
$(document).ready(function(){ $("#add").click(function(){ $("#containerDiv").append(" I should hide as well if you click me
"); }); $("body").on("click","p", function(){ $(this).hide(); }); });