jQuery最接近的TR选择

Lee*_*Lee 7 jquery jquery-selectors closest

希望有人可以提供建议.单击链接后尝试删除行时出现问题.

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>
Run Code Online (Sandbox Code Playgroud)

现在是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);
    }    
   }
  })
 });
Run Code Online (Sandbox Code Playgroud)

这应该是非常简单的,但不是删除行.只是为了踢,如果我把它改成类似的东西

$('.remove-row').addClass('foo');
Run Code Online (Sandbox Code Playgroud)

它会将foo添加到所有表行.所以可以理解为什么它不删除最近的行.

有任何想法吗 ?

谢谢高级.

Nic*_*ver 18

问题是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);
    }    
   }
  })
 });
Run Code Online (Sandbox Code Playgroud)

context选项决定什么this将会在$.ajax()回调函数,因为你希望它是在.remove-row你点击,使用this该功能.