Javascript 如何使用jQuery获取href值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2098408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get href value using jQuery?
提问by Adi Sembiring
I'm trying to get href value using jQuery:
我正在尝试使用 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>
But it doesn't work. Why?
但它不起作用。为什么?
回答by Gareth
You need
你需要
var href = $(this).attr('href');
Inside a jQuery click handler, the thisobject refers to the element clicked, whereas in your case you're always getting the href for the first <a>on the page. This, incidentally, is why your example works but your real code doesn't
在 jQuery 单击处理程序中,this对象指的是单击的元素,而在您的情况下,您总是获得<a>页面上第一个的 href 。顺便说一句,这就是为什么您的示例有效但您的真实代码无效的原因
回答by Prince Patel
You can get current href value by this code:
您可以通过以下代码获取当前的 href 值:
$(this).attr("href");
To get href value by ID
通过ID获取href值
$("#mylink").attr("href");
回答by AlfaTeK
It works... Tested in IE8 (don't forget to allow javascript to run if you're testing the file from your computer) and chrome.
它有效...在 IE8 中测试(如果您正在测试计算机上的文件,请不要忘记允许 javascript 运行)和 chrome。
回答by wangtong
if the page have one <a>It Works,but,many <a>,have to use var href = $(this).attr('href');
如果页面有一个<a>It Works,但是,很多<a>,必须使用var href = $(this).attr('href');

