我试图找出是否有可能创建一个类clicklistener.当我创建一个div侦听器时,我可以先添加侦听器,然后我可以创建div.
HTML:
<div> <div id="1"> <div id="2"> <!-- will be created.. --> </div> </div> </div>
JS:
$(".welcome").click(function() { alert("Hi there"); }); // Later the class album will be loaded // When you put it above it will work.. welcome = document.getElementById("2"); welcome.innerHTML = '<div id="3" class="welcome"> Hello</div>';
我做了jsfiddle测试.
解决方法
是的…使用
on活动代表……
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.
试试这个
$(document).on('click','.welcome',function() { alert("Hi there"); });
更好的是,如果你将事件附加到最接近的元素…在你的情况下,div是id#2< div id = 2>
$('#2').on('click',function() { alert("Hi there"); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。