JavaScript onclick.closest给出错误?
我试图将box内容(与box content类最接近的div)更新为ajax调用返回的数据,但收到一个错误 .box内容在页面上是一个由5个div组成的类,但是最近的div不应该找到最近的div吗?每个长方体都有一个长方体内容类及其父对象(如果有意义的话) Html: 错误:JavaScript onclick.closest给出错误?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我试图将box内容(与box content类最接近的div)更新为ajax调用返回的数据,但收到一个错误 .box内容在页面上是一个由5个div组成的类,但是最近的div不应该找到最近的div吗?每个长方体都有一个长方体内容类及其父对象(如果有意义的话) Html: 错误: Uncaught TypeError: Cannot read property 'html' of null at Object.success (override.js?v=1502133651:806)
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)
Uncaught TypeError:无法读取null的属性“html”
在Object.success(override.js?v=1502133651:806)
at i(jquery-3.1.1.min.js:2)
在Object.fireWith[as resolveWith](jquery-3.1.1.min.js:2)
在A(jquery-3.1.1.min.js:4)
在XMLHttpRequest。(jquery-3.1.1.min.js:4)
元素
在您的代码中是一个本机DOM节点,因为您只是将此传递给函数
这意味着您使用的是本机closest()
,而不是jQuery版本,这就是它返回null
而不是空集合的原因
你必须这样做
$(element).closest('.box-content').html(data);
但鉴于本机方法失败,jQuery的版本可能也会失败,但至少它会默默地失败
确保确实存在具有类box content
的父元素,以使最近()方法实际找到元素
人们确实想知道为什么不使用合适的事件处理程序,比如
<div id="removeButton" class="btn btn-danger btn-sm" data-id="{{ $playerRp->user_id }}">
<i class="fa fa-times"></i> Remove
</div>
而元素
从何而来?有些东西告诉我它是一个本机DOM节点,而不是jQuery元素。您正在内联onclick上传递“this”。它将不是jquery对象。将其包装在$()中,使其成为访问最近()的对象,因为元素不是jQueryHi,找不到我的.box内容,这有什么原因吗?它是一个父对象的父对象。我真的不知道问题出在哪里,因为我没有看到您的HTML,也没有看到其余的代码。通常,如果元素是element
链上某个位置的父元素,则应该找到它。
$(element).closest('.box-content').html(data);
<div id="removeButton" class="btn btn-danger btn-sm" data-id="{{ $playerRp->user_id }}">
<i class="fa fa-times"></i> 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);
},
});
});