簡體   English   中英

將行動態添加到表后,jQuery選擇器未觸發

[英]jQuery selector not firing after dynamically adding a row to a table

我有一張桌子

<table id="table1">
   <tr>
      <td>Cell 1</td>
      <td>Cell2</td>
   </tr>
</table>

在選擇單元格時

$('#table1 tr td').bind('click', function(){
     alert('Selected');
})

但是,當我動態添加單元格時

$(this.parentNode).after('<tr><td>Cell 3</td><td>Cell 4</td></tr>');

現在,當我單擊單元格3或單元格4時,不會觸發alert消息。

如何在不刷新頁面的情況下解決此問題?

用戶jquery的"on"方法代替綁定。 https://api.jquery.com/on/與bind的主要區別是它對選擇器中的元素執行某種監視並添加“實時綁定”。 這是示例: http : //jsbin.com/yapiheju/1/edit

您還必須將事件偵聽器重新分配給新的DOM節點。 在動態添加一個單元格之后,請確保您也對其設置了一個偵聽器。

jQuery docs: 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(). 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().

或者,您也可以按照其他用戶的建議,將委托事件與jQuery的on一起使用。 您要做的就是找出在DOM中比單元更接近核心文檔的元素,並確保在附加事件時將其作為真實節點顯示。 在您的情況下,最好選擇document本身,因為您無需等待整個DOM加載。

現在,只需將click事件設置為document 因此,每次單擊事件到達document (通過直接單擊或冒泡到document )時,都會觸發回調。 但是我們不想要那樣。 好吧,很簡單。 只需在事件名稱和回調之間傳遞一個參數給.on()方法即可。 此參數將是一個選擇器字符串,指向后代,該后代將允許將此特定事件冒泡到document

on使用jQuery

例如。

$(document).on("click", 
    "#table1 tr td", function(){ 
    alert('Selected'); 
}); 

此處的文檔: http : //api.jquery.com/on/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM