2014-06-10 53 views
0

我嘗試用jQuery來獲得點擊按鈕最接近Li和刪除,但似乎並不火獲得最接近李與jQuery

這裏是我的標記

<li class="dd-item dd3-item" data-id="22"> 
    <div class="dd-handle dd3-handle"></div> 
    <div class="dd3-content">some other 
     <span class="pull-right" style="display: none;"> 
      <a data-target="#settings_22" data-action="collapse" href="#"><i class="fa fa-pencil"></i></a> 
     </span> 
    </div> 

    <form method="post" action="#" class="menu_settings" style="display: block;"> 
     <input type="hidden" value="22" name="id"> 
     <fieldset> 

      <div role="toolbar" class="btn-toolbar"> 
       <div class="btn-group btn-group-sm"> 
        <button type="button" data-action="update" class="update btn btn-default"><i class="fa fa-upload"></i> Update</button> 
        <button type="button" data-action="delete" class="delete btn btn-default"><i class="fa fa-trash-o"></i> Trash</button> 
        <button type="button" class="cancel btn btn-default"><i class="fa fa-times"></i> Cancel</button>  
       </div>         
      </div> 
     </fieldset>       
    </form> 
</li> 

jQuery的

$('button.update, button.delete').on('click', function(e) { 
    e.preventDefault(); 
    var url = ajaxurl + '?action=updateCategories'; 
    var data = $(this).closest('form').serialize(); 
    var action = $(this).data('action'); 
    $.ajax({ 
     type: "POST", 
     url: url, 
     data: { 
      data: data, 
      command:action 
     }, 
     //contentType: "application/json; charset=utf-8", 
     //dataType: "json", 
     cache: false, 
     success: function(html) { 
      if (action == 'delete') { 
       alert('delete'); 
       $(this).closest('li').remove(); 
      } 
     } 
    }); 
}); 

我得到的警報,但該列表不會被刪除

+2

它工作:http://jsfiddle.net/ehsansajjad465/FzN77/ –

+2

在這裏工作 - ** [小提琴](http://jsfiddle.net/kJb9c/)** –

+0

我對我的洞做了更新jquery顯示我如何嘗試使用 – fefe

回答

1

默認情況下,成功回調執行this引用window;這可能不是你想要的。

可以使用的$.ajaxcontext選項綁定在成功回調this

$.ajax({ 
    ..., 
    context: this, 
    ... 
}); 

這可以確保使用$(this)的成功回調中會在點擊的元素。