[英]passing 'this' on onClick event function call
I have a table which look like this: 我有一张桌子,看起来像这样:
<table bordered='1'>
<tr>
<td>Apple</td><td><a href="#" onclick="delete(this);">x</a></td>
</tr>
<tr>
<td>Ball</td><td><a href="#" onclick="delete(this);">x</a></td>
</tr>
</table>
<script>
function delete(clickedOne) {
alert(clickedOne);
clickedOne.parent().parent().remove();
}
</script>
Now what I want to do is delete the "tr" which 'x' has been clicked. 现在,我要删除的是单击“ x”的“ tr”。 For this I need to let my delete function to know which 'x' has been clicked.
为此,我需要让我的删除功能知道单击了哪个“ x”。 But 'this' as a parameter seems like not working.
但是“ this”作为参数似乎无效。
Note: I can't put id in my table elements. 注意:我不能在表元素中添加id 。
First: 第一:
delete
is a reserved keyword. delete
是保留关键字。 If you looked at your JavaScript console you would see an error like: 如果您查看JavaScript控制台,则会看到类似以下的错误:
Uncaught SyntaxError: Unexpected token delete
未捕获的SyntaxError:意外删除令牌
Call your function something else. 调用其他函数。
Second: 第二:
clickedOne
is a DOM Node but parent()
is a jQuery method. clickedOne
是DOM节点,而parent()
是jQuery方法。
You want clickedOne.parentNode.parentNode
to reach the tr
element (and then you want to call removeChild
on the table row's parent element). 您希望
clickedOne.parentNode.parentNode
到达tr
元素(然后您要在表行的父元素上调用removeChild
)。
i would suggest you to use jquery, because the dom handling is easier and it's also the proper way to separate javascript from html 我建议您使用jquery,因为dom处理更容易,它也是将javascript与html分开的正确方法
if you wanted to use jquery, a better way than using parent().parent() ist to get all parents and filter them. 如果您想使用jquery,比使用parent()。parent()更好的方法是获取所有父对象并对其进行过滤。
$(function() {
$(".myTable a").click(function(){
$(this).parents('tr').remove();
});
});
and change your html like this: 并像这样更改您的html:
<table bordered='1' class="myTable">
<tr>
<td>Apple</td><td><a href="#">x</a></td>
</tr>
<tr>
<td>Ball</td><td><a href="#">x</a></td>
</tr>
</table>
you can test it on the fiddle: http://jsfiddle.net/SP2X9/ 您可以在小提琴上对其进行测试: http : //jsfiddle.net/SP2X9/
you can just give class and onclick function enter code here 你可以给class和onclick函数在这里输入代码
<a href="#" class="delete_row">x</a>
$(function() {
$(".delete_row").click(function(){
$(this).closest('tr').remove();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.