[英]Delete a table row with javascript / jquery
這不起作用。 Firebug並沒有拋出任何錯誤。
HTML:
<table>
<tr><td>BookA</td><td><a href="javascript:deleteRow($(this));" class="red">Delete</a></td></tr>
<tr><td>BookB</td><td><a href="javascript:deleteRow($(this));" class="red">Delete</a></td></tr>
<tr><td>BookC</td><td><a href="javascript:deleteRow($(this));" class="red">Delete</a></td></tr>
<tr><td>BookD</td><td><a href="javascript:deleteRow($(this));" class="red">Delete</a></td></tr>
</table>
使用Javascript:
function deleteRow(ref) {
$(ref).parent().parent().remove();
}
如果可能的話,我想使用內聯javascript的解決方案
首先,內聯JavaScript( href="javascript:x"
或onclick="x"
)通常很糟糕。 使用內聯JavaScript,您將無法訪問事件對象,並且您無法確定this
引用的是什么。
jQuery(以及幾乎所有其他JavaScript庫/框架)都具有內置事件處理功能。 因此,使用事件處理程序,您的代碼看起來像這樣:
$('a.red').click(function(e) {
e.preventDefault(); // don't follow the link
$(this).closest('tr').remove(); // credits goes to MrKurt for use of closest()
});
這是一個演示: http : //jsbin.com/okaxu
嘗試這個:
// Bind all the td element a click event
$('table td.deleteRow').click(function(){
$(this).parent().remove();
});
順便說一句,它將從你的HTML代碼中刪除javascript。 有了這個HTML代碼
<table>
<tr>
<td>BookA</td>
<td class="red deleteRow">Delete</td>
</tr>
<tr>
<td>BookB</td>
<td class="red deleteRow">Delete</td>
</tr>
<tr>
<td>BookC</td>
<td class="red deleteRow">Delete</td>
</tr>
<tr>
<td>BookD</td>
<td class="red deleteRow">Delete</td>
</tr>
</table>
這是行不通的,因為$(this)並不像你想的那樣引用a-tag(我認為它指的是window對象或其他東西)
而不是在href屬性中使用內聯javascript來執行此操作
而是這樣做
<script type="text/javascript">
$("table a").click( function() {
$(this).parent().parent().remove();
});
</script>
刪除內聯腳本
<script>
$(function(){
$('table td a').live('click', function(){
$(this).parents('tr').remove();
return false;
});
});
</script>
我相信你的deleteRow函數有一個錯誤。 這是它應該如何寫:
function deleteRow(ref) {
ref.parent().parent().remove();
}
您傳遞給deleteRow的引用已經是一個jQuery對象。 你不應該使用$(ref),只是ref,因為ref已經是一個jQuery對象。
我不得不同意應該避免使用內聯javascript,但是如果有其他原因使用它是必要或有益的,那么就是這樣的。
<table>
<tr><td>BookA</td><td><a href='#' onclick="$(this).parents('tr').remove(); return false;" class="red">Delete</a></td></tr>
<tr><td>BookB</td><td><a href='#' onclick="$(this).parents('tr').remove(); return false;" class="red">Delete</a></td></tr>
<tr><td>BookC</td><td><a href='#' onclick="$(this).parents('tr').remove(); return false;" class="red">Delete</a></td></tr>
<tr><td>BookD</td><td><a href='#' onclick="$(this).parents('tr').remove(); return false;" class="red">Delete</a></td></tr>
</table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.