2015-04-19 166 views
0

我有一張表,我正在動態添加新行。 帶線添加它看起來像這樣:刪除表中動態創建的行

<table> 
<tbody id="list"> 
    <tr> 
    <td>A</td> 
    <td>B</td> 
    <td>C</td> 
    </tr> 
    <tr class="new1">       // 
    <td class="new1">D</td>     // 
    <td class="new1">E</td>     // These lines 
    <td class="new1">       // are dynamic 
     <a href="#confirm" class="new1">X</a> // 
    </td>          // 
    </tr>          // 
</body> 
</table> 

我希望能夠通過單擊最後一列時會被重定向我的對話框,確認X符號單獨刪除新的生產線。 對話框很簡單 - 兩個按鈕:是/否。

我的想法是獲取點擊元素的類,將其保存爲變量,然後在單擊yes按鈕時使用它來刪除具有該特定類的所有元素。

腳本我做了這個樣子的:

// For saving class of clicked link in list 
var delId; 
$(document).on("click", "#list a", function(){ 
    delId= $(this).attr("class"); 
}); 

// Then I try to remove elements by class 
$("#idOfYesButton").click(function(){ 
    $("."+delId).remove(); 
}); 

但它在某種程度上什麼都不做,我不明白爲什麼,所以如果你能告訴我哪裏做錯了這將是大多是讚賞。

+0

''應該是''。這是一個複製錯誤還是在真實的代碼? – Barmar

+0

這裏工作:http://jsfiddle.net/barmar/r9pbj2bd/3/。在$(document).ready()'裏面有'#idOfYesButton'處理程序嗎? – Barmar

回答

1

嘗試這樣:​​

<table> 
    <tr class="new1"> 
     <td class="new1">D</td> 
     <td class="new1">E</td> 
     <td class="new1"> <a href="#" class="remove">X</a> 
     </td> 
    </tr> 
    <tr class="new1"> 
     <td class="new1">D</td> 
     <td class="new1">E</td> 
     <td class="new1"> <a href="#" class="remove">X</a> 
     </td> 
    </tr> 
    <tr class="new1"> 
     <td class="new1">D</td> 
     <td class="new1">E</td> 
     <td class="new1"> <a href="#" class="remove">X</a> 
     </td> 
    </tr> 
</table> 

jQuery的

$(".remove").click(function() { 
    if (confirm("sure you want to delete?") === true) { 
    $(this).closest('tr').remove(); 
    } 
    else return; 
}); 
0

試試這個腳本

$(document).on("click", "#list tr td a", function(){ 
    if(confirm($(this).attr("class"))) 
     $("."+$(this).attr("class")).remove(); 
});