<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("h2").html("<p class='test'>click me</p>")
});
$(".test").click(function(){
alert();
});
});
</script>
</head>
<body>
<h2></h2>
<button>generate new element</button>
</body>
</html>
我试图通过单击按钮在<h2>中生成一个类名为test的新标记。我还定义了一个与test关联的单击事件。但是这个事件不起作用。
有人能帮忙吗?
我在jQuery的文档中找到了两个解决方案:
首先:在Body或Document上使用委托
例句:
$("body").delegate('.test', 'click', function(){
...
alert('test');
});
Why?
答:根据一组特定的根元素,为现在或将来与选择器匹配的所有元素附加一个或多个事件处理程序。
链接:http://api.jquery.com/delegate/
第二步:将你的函数放在"$(document)"中,使用"on"并将它附加到你想要触发这个函数的元素上。
第一个参数是“事件处理器”,第二个参数是元素,第三个参数是函数。
例句:
$( document ).on( 'click', '.test', function () {
...
alert('test');
});
Why?
Answer: Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next ...
link: https://api.jquery.com/on/
原因:
在jQuery中,Click()事件直接绑定,仅当特定元素(Html代码)存在于页面(页面加载后)时,将事件处理程序附加到元素上。
动态元素是在javascript或jquery的帮助下创建的(不是在Html中)。
它不会考虑页面加载后创建的未来元素(Dynamic)。
因此,正常的单击事件不会在动态元素上触发。
解决方案:
为了克服这个问题,我们应该使用on()函数。On()可以为当前元素和未来元素委托事件。
委托事件的优点是可以将处理程序附加到将来要添加到文档中的元素。
注意:delegate(),live()和on()函数比DOM元素更有优势。从JQuery 1.7开始,delegate()和live()已弃用(不要使用它们)。
可以同时为当前和未来的元素委托事件。
你的代码应该是这样的
从$(document).ready中删除代码:
$(".test").click(function(){
alert();
});
改变为:
$(document).on('click','.test',function(){
alert('Clicked');
});
我不能让live或委托在一个灯箱(小盒子)中的div上工作。
我成功地使用了setTimeout,以以下简单的方式:
$('#displayContact').click(function() {
TINY.box.show({html:'<form><textarea id="contactText"></textarea><div id="contactSubmit">Submit</div></form>', close:true});
setTimeout(setContactClick, 1000);
})
function setContactClick() {
$('#contactSubmit').click(function() {
alert($('#contactText').val());
})
}