jQuery 最接近的 TR 选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3548762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery closest TR selection
提问by Lee
Hope someone can advise. Having issues trying to remove a row once a link has been clicked.
希望有人能指教。单击链接后尝试删除行时遇到问题。
HTML
HTML
<table>
<tr><td>Some Data</td><td><a href="#" class="remove-row>Remove Row</a></td></tr>
<tr><td>Some Data</td><td><a href="#" class="remove-row">Remove Row</a></td></tr>
</table>
Now the JS
现在的JS
$("a.remove-row").live('click', function(eve){
eve.preventDefault();
$.ajax({
type: 'GET',
url: '/someaction/',
dataType: 'json',
success: function(msg){
if(msg.error){
alert(msg.error);
}else{
$(this).closest('tr').remove();
alert(msg.success);
}
}
})
});
This should be real simple buts its not removing the row. Just for kicks if I change it to something like
这应该很简单,但它不会删除该行。只是为了踢,如果我把它改成类似的东西
$('.remove-row').addClass('foo');
It will add foo to all table rows. So can understand why its not removing the closest row.
它会将 foo 添加到所有表行。所以可以理解为什么它不删除最近的行。
Any Ideas ?
有任何想法吗 ?
Thank in advanced.
先谢谢了。
回答by Nick Craver
The problem is this
currently refers to the ajax object in your success
callback, but it's an easy fix, use the content
option like this:
问题this
当前是指success
回调中的 ajax 对象,但这是一个简单的修复,使用如下content
选项:
$("a.remove-row").live('click', function(eve){
eve.preventDefault();
$.ajax({
context: this, //add this here!
type: 'GET',
url: '/someaction/',
dataType: 'json',
success: function(msg){
if(msg.error){
alert(msg.error);
}else{
$(this).closest('tr').remove();
alert(msg.success);
}
}
})
});
The context
option dictates what this
will be in the $.ajax()
callback functions, since you want it to be the .remove-row
you clicked on, use this
as the option.
该context
选项决定this
了$.ajax()
回调函数中的内容,因为您希望它是.remove-row
您单击的那个,this
用作选项。
回答by NicolasT
Nick's answer should work, but you can do this too, I don't know which one is better, probably Nick's one, but it may help anyway...
尼克的答案应该有效,但你也可以这样做,我不知道哪个更好,可能是尼克的答案,但无论如何它可能会有所帮助......
$("a.remove-row").live('click', function(eve){
var row = this;
eve.preventDefault();
$.ajax({
type: 'GET',
url: '/someaction/',
dataType: 'json',
success: function(msg){
if(msg.error){
alert(msg.error);
}else{
$(row).closest('tr').remove();
alert(msg.success);
}
}
})
});
回答by Tyler
Wouldn't it be easier to do the remove/hide before hand?
事先进行删除/隐藏不是更容易吗?
like this :
像这样 :
$("a.remove-row").live('click', function(eve){
$(this).hide();
<The rest of your code logic>
......