简体   繁体   中英

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

the subject is pretty descriptive of my problem, I am assuming it won't work this way, is there a way to make it work? (workaround)?

Here is the code that is loaded via 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>

Here is my click event:

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

Do this.

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

or

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

 });

Edit:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate().

you have to re-attach the event handlers to the dynamically added elements into the DOM. .live method was used widely but now its deprecated. In jQuery version 1.7+ you can use .on or alternatively you can use .delegate

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

});

using delegate

$(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); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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