我尝试使用 jQuery 获取 anchor 标记的 href
值,但 this
关键字未按预期工作。
这是控制台中代码的结果:
<小时/>我有问题的代码部分:
$('#container a').click(() => {
console.log(this);
let link = $(this).attr("href");
console.log("from jquery - " + link);
//chrome.tabs.create({ url: link });
});
如您所见,this
关键字指向 window
对象。
此代码是我尝试为 Opera 构建的扩展的一部分。
最佳答案
您正在使用箭头函数 () => {..}
而不是常规函数 function () {...}
,这就是为什么您的 this
没有按您的预期工作。
所以代替这个:
$('#container a').click(() => { ... });
使用这个:
$('#container a').click(function() { ... });
您更新的代码:
$('#container a').click(function () {
console.log(this);
let link = $(this).attr('href');
console.log(link);
})
或与箭头函数:
$('container a').click(event => {
let link = $(event.currentTarget).attr('href');
console.log(link);
})
<小时/>
有关箭头函数的更多信息:
关于javascript - 无法使用 jQuery 获取 anchor 标记的 href 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51088222/