繁体   English   中英

无法使用jQuery获得锚标记的href值

[英]Can't get the href value of an anchor tag with jQuery

我正在尝试使用jQuery获取锚标记的href值,但this关键字无法正常工作。

源代码

这是控制台中代码的结果:

devtools控制台


我有问题的代码部分:

$('#container a').click(() => {
    console.log(this);
    let link = $(this).attr("href");
    console.log("from jquery - " + link);
    //chrome.tabs.create({ url: link });
});

如您所见, this关键字指向window对象。 这段代码是我正在尝试为Opera构建的扩展的一部分。

这将为您提供href值

var href = $('a').attr('href');

这是要在此处测试的示例:

 $(document).ready(function() { $("a").click(function(event) { var href = $(event.target).attr('href'); //this will give you the href value alert(href); event.preventDefault(); }); }); 
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <a href="I'm the href value">this is a test link, click me</a> 

您使用的是箭头函数 () => {..}而不是常规的函数function () {...} ,这就是为什么this function () {...}无法按预期工作的原因。

所以代替这个:

$('#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);
})

有关箭头功能的更多信息:

不要使用箭头函数( () => {} ),请使用经典函数声明( function() {} )。 箭头函数不会this绑定到当前范围。

$("#container a").click(function(){
    console.log(this);
    let link = $(this).attr("href");
    console.log(link);
})

您可以在此处了解有关箭头功能的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM