2017-08-07 118 views
-2

我試圖更新從ajax調用返回的數據,但我收到一個錯誤框內容(與盒內容的類最接近的div)。JavaScript onclick .closest給出錯誤?

.box-content是頁面上5個div的類,但不應該最近能找到最接近的一個嗎?如果有意義的話,每個盒子都有一個盒子內容類及其父代的父代?

HTML:

<div style="margin-top:12%;" id="removeButton" class="btn btn-danger btn-sm" onclick="fireGovernmentMember({{ $playerRp->user_id }}, this);"><i class="fa fa-times"></i> &nbsp;Remove</div> 

的Javascript:

function fireGovernmentMember(playerId, element) { 
    $.ajax({ 
     url: '/' + 'api/ajax/owner/fire_gov', 
     type: "GET", 
     data: { 
      player_id: playerId, 
     }, 
     statusCode: { 
      400: function (response) { 
       showErrorNotification("Something went wrong", response.responseText, 3000); 
      }, 
      500: function (response) { 
       showErrorNotification("Something went wrong", response.responseText, 3000); 
      } 
     }, 
     success: function(data) { 
      element.closest('.box-content').html(data); 
      showSuccessNotification("Action Completed", "Item has been removed from user.", 1000); 
     }, 
    }); 
} 

錯誤:

Uncaught TypeError: Cannot read property 'html' of null 
    at Object.success (override.js?v=1502133651:806) 
    at i (jquery-3.1.1.min.js:2) 
    at Object.fireWith [as resolveWith] (jquery-3.1.1.min.js:2) 
    at A (jquery-3.1.1.min.js:4) 
    at XMLHttpRequest.<anonymous> (jquery-3.1.1.min.js:4) 
+0

在哪裏,'element'哪裏來的?東西告訴我這是一個本地DOM節點,而不是一個jQuery元素 – adeneo

+0

您正在傳遞'this'到內聯onclick上。它不會是一個jQuery對象。將它包裝在$()中,使其成爲訪問最接近的對象() – Taplar

+0

,因爲元素不是jQuery – epascarello

回答

2

element在你的代碼是土生土長的DOM節點,因爲你只是this傳遞給功能。

這意味着您使用的是原生closest()而不是jQuery的版本,這就是爲什麼它返回null而不是空集合。

你要做

$(element).closest('.box-content').html(data); 

但看到本機方法失敗,jQuery的版本可能會爲好,但至少它會靜靜地失敗。

確保實際上有box-content類的父元素,以使closest()方法實際找到一個元素。

一個人想知道爲什麼你會不使用正確的事件處理程序,而不是,像

<div id="removeButton" class="btn btn-danger btn-sm" data-id="{{ $playerRp->user_id }}"> 
    <i class="fa fa-times"></i> &nbsp;Remove 
</div> 

然後

$('#removeButton').on('click', function() { 
    var playerId = $(this).data('id'); 
    var self  = $(this); 

    $.ajax({ 
     url: '/' + 'api/ajax/owner/fire_gov', 
     type: "GET", 
     data: { player_id: playerId }, 
     statusCode: { 
      400: function (response) { 
       showErrorNotification("Something went wrong", response.responseText, 3000); 
      }, 
      500: function (response) { 
       showErrorNotification("Something went wrong", response.responseText, 3000); 
      } 
     }, 
     success: function(data) { 
      self.closest('.box-content').html(data); 
      showSuccessNotification("Action Completed", "Item has been removed from user.", 1000); 
     }, 
    }); 
}); 
+0

嗨,我的.box內容未找到,是否有這樣的原因?它是父母的父母。 –

+0

我真的不知道問題是什麼,因爲我沒有看到您的HTML,也沒有看到其他代碼。一般來說,如果元素是父元素上的某個父元素,它應該找到它。 – adeneo