繁体   English   中英

jQuery click()事件没有触发加载AJAX的HTML元素

[英]jQuery click() event not firing on AJAX loaded HTML elements

这个主题很好地描述了我的问题,我假设它不会以这种方式工作,有没有办法使它工作? (解决方法)?

这是通过AJAX加载的代码:

<div>
<div id="s0frame" class="sframe"></div>
<div id="s1frame" class="sframe"></div>
<div id="s2frame" class="sframe"></div>
<div id="s3frame" class="sframe"></div>
<div id="s4frame" class="sframe"></div>
<div id="s5frame" class="sframe"></div>
<div id="chatframe" class="chat alpha60"></div>
</div>

这是我的点击事件:

$('.sframe').bind('click', function() { 
    var seat_number = this.id.match(/\d/g);
    alert(seat_number); 
});

做这个。

 $(document).on("click",".sframe",function(e){
 var seat_number = this.id.match(/\d/g);
 alert(seat_number); 
 });

要么

 $(document).delegate(".sframe","click",function(e){
 var seat_number = this.id.match(/\d/g);
 alert(seat_number); 

 });

编辑:

从jQuery 1.7开始,不推荐使用.live()方法。 使用.on()附加事件处理程序。 旧版jQuery的用户应该使用.delegate()。

您必须将事件处理程序重新附加到DOM中的动态添加元素。 .live方法被广泛使用但现在已被弃用。 在jQuery 1.7+版本中,您可以使用.on或者您也可以使用.delegate

$(document).on("click",".sframe",function(e){

});

使用代表

$(document).delegate(".sframe","click",function(e){

});

除非在将标记加载到页面之后调用.bind()函数,否则需要使用其他函数,如.live(),或者最好使用最新版本的jQuery,.on(),因为只有.bind()目标DOM元素在运行时已存在,而.live()和.on()为您提供不同的范围选项,用于跟踪添加到页面的元素。

$(document).on('click','sframe', function() { 
    var seat_number = this.id.match(/\d/g);
    alert(seat_number); 
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM