我正在尝试使用jQuery获取href值:
<html>
<head>
<title>Jquery Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function(event) {
alert("As you can see, the link no longer took you to jquery.com");
var href = $('a').attr('href');
alert(href);
event.preventDefault();
});
});
</script>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
</body>
</html>
但它不起作用。为什么?
发布于 2010-01-20 09:38:48
你需要
var href = $(this).attr('href');
在jQuery单击处理程序中,this
对象引用所单击的元素,而在本例中,您总是获得页面上第一个<a>
的href。顺便说一句,这就是为什么你的示例可以工作,但你的真实代码却不行的原因
发布于 2017-01-20 16:45:57
您可以通过以下代码获取当前href值:
$(this).attr("href");
通过ID获取href值
$("#mylink").attr("href");
发布于 2020-06-29 02:26:18
值得一提的是
$('a').attr('href'); // gets the actual value
$('a').prop('href'); // gets the full URL always
https://stackoverflow.com/questions/2098408
复制相似问题