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

我试图找出是否有可能创建一个类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");
});

fiddle here

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...