簡體   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