[英]Can't get the href value of an anchor tag with jQuery
这将为您提供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.