我试图找出是否有可能创建一个类clicklistener.当我创建一个div侦听器时,我可以先添加侦听器,然后我可以创建div. 所以我想先创建一个监听器,然后再添加该类.可能吗? HTML: div div id="1
所以我想先创建一个监听器,然后再添加该类.可能吗?
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', '.welcome', function() { alert("Hi there"); });
fiddle here