[英]Delete HTML table row dynamically using javascript with row index with link
我想動態地添加/刪除HTML中的表行。 我知道這個論壇中有很多類似查詢的問題。 我的疑問是使刪除操作適用於每一行。 為此,我使用了表索引。
//Link
var cell7 = row.insertCell(6);
var element7 = document.createElement("a");
var text = document.createTextNode("Delete");
element7.appendChild(text);
element7.setAttribute("href","javascript:deleterow("+rowcount+")");
element7.name="reqlink[]";
cell7.appendChild(element7);
這里rowcount是當前添加的行的索引。 因此,在添加行的同時,我還定義了刪除動作。 因此,每一行都有一個刪除鏈接。 但是,問題在於索引是動態變化的。 因此,該解決方案將無法真正起作用。
請你幫忙 我不想使用該解決方案之一定義的復選框。
刪除行函數的腳本如下:
function deleterow(index){
alert('working' + index);
table.deleteRow(index);
}
#########嘗試過此###########
//Link
var cell7 = row.insertCell(6);
var element7 = document.createElement("a");
var text = document.createTextNode("Delete");
element7.appendChild(text);
element7.setAttribute("href","javascript:deleterow(this); return false");
element7.name="reqlink[]";
cell7.appendChild(element7);
“ this”指向窗口而不是表行。
解決方案是將當前行元素傳遞給deleteRow函數,並使用其父元素將其刪除(您不能直接將其刪除),因此函數將如下所示:
var deleteRow = function (link) {
var row = link.parentNode.parentNode;
var table = row.parentNode;
table.removeChild(row);
}
以下是用於刪除鏈接的HTML
<a onclick="javascript:deleteRow(this); return false;">
使用以下行動態創建元素(也請注意大寫和小寫字符):
element7.setAttribute("onclick","deleteRow(this); return false");
因此,無需使用ID來刪除行。 希望這會有所幫助。
不要使用該行的索引。 在很多層面上都是錯誤的。 假設您刪除了第1 3個單元格,並且您的索引已更改。 如果要刪除第4行,它將實際刪除第7行,而不是實際表中的第4行。
在您的字段中添加一個“數據ID”字段,每一行都有一個唯一的ID。 使用它來刪除行。
更好的解決方案:這是在jQuery中,因此請找到等效的js原型。
$(this).closest("tr").html("")
$(this)是被單擊的按鈕。 按鈕的'click'事件也是如此。
according to Aditya Shedge use closest itself. u can see closet definition here: http://api.jquery.com/closest/
here is an example:
<table id="foo" border="1">
<tr>
<td>check</td>
<td><input type="text></td>
<td><input type="text></td>
<td><input type="button" class="addButton" value="add"/></td>
<td><input type="button" class="deleteButton" value="delete"/></td>
</tr>
</table>
<script>
$(function(){
$(".addButton").click(function(){
$(this).closest("tr").clone(true).appendTo("#foo");
});
$(".deleteButton").click(function(){
$(this).closest("tr").remove();
});
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.