当前位置 : 主页 > 网页制作 > JQuery >

jquery – 单击将在稍后创建的侦听器类

来源:互联网 收集:自由互联 发布时间:2021-06-15
我试图找出是否有可能创建一个类clicklistener.当我创建一个div侦听器时,我可以先添加侦听器,然后我可以创建div. 所以我想先创建一个监听器,然后再添加该类.可能吗? HTML: div div id="1
我试图找出是否有可能创建一个类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', '.welcome', function() {
   alert("Hi there");
});

fiddle here

网友评论