使用javascript / jquery删除表行 [英] Delete a table row with javascript / jquery

查看:74
本文介绍了使用javascript / jquery删除表行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不起作用。 Firebug并没有抛出任何错误。

This is not working. Firebug is not throwing any error though.

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:

Javascript:

function deleteRow(ref) {   
    $(ref).parent().parent().remove(); 
 }

如果可能,我想使用内联javascript的解决方案

推荐答案

首先,内联JavaScript( href =javascript:x onclick =x)通常很糟糕。使用内联JavaScript,您将无法访问事件对象,并且您无法确定引用的内容。

First of all, inline JavaScript (href="javascript:x" or onclick="x") is generally bad. With inline JavaScript, you won't have access to the event object, and you can't really be sure what this references to.

jQuery(以及几乎所有其他JavaScript库/框架)都内置了事件处理功能。所以,你的代码与事件处理程序一样:

jQuery (and almost every other JavaScript library/framework) has built-in event handling. So, your code would look like this with event handlers:

$('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

这篇关于使用javascript / jquery删除表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆