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

jQuery绑定click事件无法获取点击元素属性,返回undefined问题排查

问题原因与解决方案

问题根源

你在<a>元素的点击事件处理中使用了箭头函数,箭头函数不会绑定自身的this,它的this继承自外层作用域(此处为全局window对象),因此this根本不是你点击的<a>元素,自然无法获取到它的属性,所有返回值都是undefined。

另外还有个次要问题:touchstart, touchend事件名里的逗号是错误写法,jQuery绑定多个事件应该用空格分隔,不需要逗号,不过这不是导致属性获取失败的直接原因。

修复方案

方案1:替换箭头函数为普通函数

将点击事件的箭头函数改为普通函数,此时this会自动指向触发事件的<a>元素:

$("#main").on("touchstart touchend", () => {
  console.log("touch zone");
})

$(document).on("click", "#main a", function(e) {
    e.preventDefault();

    var ab = this.nodeName;
    var cd = $(this).prop("nodeName");
    var ef = $(this).attr("href");
    
    console.log("Button click NODENAME> "+ab);
    console.log("Button click NODENAME> "+cd);
    console.log("Button click ATTR> "+ef);
});

方案2:通过事件对象获取目标元素

如果要保留箭头函数,可以利用事件参数e的target属性获取触发事件的DOM元素:

$("#main").on("touchstart touchend", () => {
  console.log("touch zone");
})

$(document).on("click", "#main a", (e) => {
    e.preventDefault();
    const targetEl = e.target;

    var ab = targetEl.nodeName;
    var cd = $(targetEl).prop("nodeName");
    var ef = $(targetEl).attr("href");
    
    console.log("Button click NODENAME> "+ab);
    console.log("Button click NODENAME> "+cd);
    console.log("Button click ATTR> "+ef);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 21:00:28