JavaScript onclick .closest会出错吗?

时间:2017-08-07 19:24:46

标签: javascript jquery html css

我正在尝试将来自ajax调用的返回数据的box-content(最近div与box-content类)更新,但是我收到错误。

.box-content是页面上5个div的类但不应该最近才能找到最近的一个?每个方框都有一个box-content类,如果有意义,它是父级的父级?

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)

1 个答案:

答案 0 :(得分: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);
        },
    });
});