我一直在使用我在這裏發現的jQuery腳本來突出顯示錶單中的行,或者在單擊它們時忽略行中的行。該腳本是:委託的jQuery事件不適用於動態添加的元素
$(".clickable-row").click(function(){
if($(this).hasClass('row-highlight'))
$(this).removeClass('row-highlight');
else
$(this).addClass('row-highlight').siblings().removeClass('row-highlight');
}
所有在我的錶行有一個類可點擊行。
這對我來說一直很好,直到我引入了一個表格,當用戶單擊一個按鈕時,它會動態添加行。在該表中,動態添加的行不會突出顯示。
我不以任何方式,但一些研究,我發現,通過使用事件代表團,動態添加的行應該是點擊後jQuery的專家,所以我改變了我的腳本是:
$(".clickable-row").on("click", "td", function() {
if ($(this).parent().hasClass('row-highlight')) {
$(this).parent().removeClass('row-highlight');
} else {
$(this).parent().siblings().removeClass('row-highlight');
$(this).parent().addClass('row-highlight');
}
});
這適用於我的靜態表,但仍然無法在動態添加的行上工作。
我已經檢查了HTML的動態添加行,他們是這樣的:
<tr class="clickable-row">
<td>some text here</td>
<td class="hidden"><input type="text" name ="ID2" value="2"></td>
HTML結構是完全一樣在同一個表中現有的行。這些行包含在標籤中。
我哪裏錯了?
編輯:出於某種原因,代碼塊顯示不正確。在html示例的末尾有一個「/ tr」標籤,但它並未顯示在問題中。
.clickable行是動態的元素,也因此,試圖事件附加到表(靜態父)。 – sinisake