7

希望有人可以建议。单击链接后尝试删除行时遇到问题。

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>

现在的 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);
    }    
   }
  })
 });

这应该很简单,但它不会删除该行。如果我把它改成类似的东西,只是为了好玩

$('.remove-row').addClass('foo');

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

有任何想法吗 ?

感谢先进。

4

4 回答 4

19

问题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);
    }    
   }
  })
 });

context选项规定this$.ajax()回调函数中的内容,因为您希望它是.remove-row您单击this的选项,请用作选项。

于 2010-08-23T15:00:10.767 回答
2

尼克的答案应该有效,但你也可以这样做,我不知道哪个更好,可能是尼克的一个,但无论如何它可能会有所帮助......

$("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);
    }    
   }
  })
 });
于 2010-08-23T15:05:09.457 回答
0

class="remove-row您在第一行有未关闭的属性。

看这里

于 2010-08-23T15:02:52.753 回答
0

事先进行删除/隐藏会不会更容易?

像这样 :

$("a.remove-row").live('click', function(eve){
      $(this).hide();
      <The rest of your code logic>
         ......
于 2010-08-23T16:43:10.500 回答