jQuery 如何使用jquery获取点击链接的href?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5508021/
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 the clicked link's href with jquery?
提问by Jin Yong
Does anyone know how can I get the clicked link's href with jquery? I have the link as following:
有谁知道如何使用 jquery 获得点击链接的 href ?我有以下链接:
<a href="ID=1" class="testClick">Test1.</a>
<br />
<a href="ID=2" class="testClick">Test2.</a>
<br />
<a href="ID=3" class="testClick">Test3.</a>
I wrote a code as following to get the href value from the link I clicked on. But somehow this is always return me the 1st link's href (ID=1) even though I clicked on Test2 or Test3. Does anyone know what is it going on here? and how can I solve this issue?
我编写了如下代码以从我单击的链接中获取 href 值。但不知何故,即使我点击了 Test2 或 Test3,这总是返回给我第一个链接的 href (ID=1)。有谁知道这里发生了什么?我该如何解决这个问题?
$(".testClick").click(function () {
var value = $(".testClick").attr("href");
alert(value );
});
回答by Daff
thisin your callback function refers to the clicked element.
回调函数中的this指的是被点击的元素。
$(".addressClick").click(function () {
var addressValue = $(this).attr("href");
alert(addressValue );
});
回答by Matt
You're looking for $(this).attr("href");
您正在寻找 $(this).attr("href");
回答by Paul
$(".testClick").click(function () {
var value = $(this).attr("href");
alert(value );
});
When you use $(".className") you are getting the set of all elements that have that class. Then when you call attr it simply returns the value of the first item in the collection.
当您使用 $(".className") 时,您将获得具有该类的所有元素的集合。然后,当您调用 attr 时,它只返回集合中第一个项目的值。
回答by vishal ribdiya
Suppose we have three anchor tags like ,
假设我们有三个锚标签,例如,
<a href="ID=1" class="testClick">Test1.</a>
<br />
<a href="ID=2" class="testClick">Test2.</a>
<br />
<a href="ID=3" class="testClick">Test3.</a>
now in script
现在在脚本中
$(".testClick").click(function () {
var anchorValue= $(this).attr("href");
alert(anchorValue);
});
use thiskeyword instead of className (testClick)
使用此关键字代替 className (testClick)