我正在尝试使用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>
但这是行不通的。为什么?
你需要
var href = $(this).attr('href');
在jQuery click处理程序内,该this
对象指的是被单击的元素,而在您的情况下,您总是<a>
在页面的第一个获得href 。顺便说一句,这就是为什么您的示例可以工作,但您的实际代码却不能工作
您可以通过以下代码获取当前的href值:
$(this).attr("href");
通过ID获取href值
$("#mylink").attr("href");
值得一提的是
$('a').attr('href'); // gets the actual value
$('a').prop('href'); // gets the full URL always
它可以工作...在IE8中测试(如果要从计算机测试文件,请不要忘记允许javascript运行)和chrome。
如果页面上有一个可以使用<a>
,但是<a>
,必须使用var href = $(this).attr('href');
本文地址:http://javascript.askforanswer.com/ruheshiyongjqueryhuodehrefzhi.html
文章标签:javascript , jquery
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
文章标签:javascript , jquery
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!