You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery自定义点击函数内$(this)不生效,无法操作父元素怎么办

问题根源

你通过内联onclick属性调用自定义函数时,函数内部的this默认绑定的是全局window对象,而非触发点击的按钮元素,所以$(this)无法获取到你要操作的目标DOM。

解决方案(任选一种即可)

方案1:调用时主动传入当前元素(改造成本最低)

  1. 修改HTML中onclick的调用逻辑,把当前元素this作为参数传给accountConfirm:
<button type="button" id="deleteScrollTop" class="btn btn-delete"
        onclick="accountConfirm(this, jsResources.addressDeleteQuestion,jsResources.addressDeleteTitle, jsResources.yes,jsResources.no ,function(res){
            if(res){
                window.location.href = '@(Url.RouteUrl("CustomerAddressDelete", new {addressId = address.Id}))'
            }
        })">
    <img src="@Url.ThemeFolderUrl("_images/delete.png")" alt="delete address" />
</button>
  1. 调整accountConfirm的参数接收逻辑,用传入的元素代替原来的$(this)操作:
function accountConfirm(element, message, title, yes_label, no_label, callback) {
    // 现在$(element)就是触发点击的按钮,操作父级直接用$(element).parent()即可
    console.log($(element));
    $("#accountConfirmModal").attr('data-confirm-yes', false);
    if ($("#accountConfirm").length == 0) {
        // 原有逻辑不变
    }
    $("#accountConfirmModal .content p").html(message || "");
};

方案2:用call手动绑定this指向(无需调整函数参数)

直接修改HTML中onclick的调用方式,用call把函数内部的this绑定为当前触发元素:

<button type="button" id="deleteScrollTop" class="btn btn-delete"
        onclick="accountConfirm.call(this, jsResources.addressDeleteQuestion,jsResources.addressDeleteTitle, jsResources.yes,jsResources.no ,function(res){
            if(res){
                window.location.href = '@(Url.RouteUrl("CustomerAddressDelete", new {addressId = address.Id}))'
            }
        })">
    <img src="@Url.ThemeFolderUrl("_images/delete.png")" alt="delete address" />
</button>

修改后原accountConfirm函数里的$(this)就可以正常获取到触发点击的按钮元素了。

方案3:移除内联onclick,用jQuery绑定事件(更符合规范的写法)

  1. 删掉HTML按钮标签里的所有onclick内容。
  2. 新增JS事件绑定逻辑:
$('#deleteScrollTop').on('click', function() {
    // 此处this就是触发点击的按钮,提前存为变量供回调使用
    const triggerBtn = this;
    accountConfirm(jsResources.addressDeleteQuestion,jsResources.addressDeleteTitle, jsResources.yes,jsResources.no ,function(res){
        if(res){
            // 要操作父级直接调用$(triggerBtn).parent()即可
            window.location.href = '@(Url.RouteUrl("CustomerAddressDelete", new {addressId = address.Id}))'
        }
    })
})

内容的提问来源于stack exchange,提问作者idiltugba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 19:09:03