如何获得与 jquery 点击链接的 href?

有人知道如何使用 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>

我编写了如下代码来从我点击的链接中获取 href 值。但不知为何,即使我单击 Test2或 Test3,它也总是返回第一个链接的 href (ID = 1)。有人知道这是怎么回事吗?我怎样才能解决这个问题呢?

    $(".testClick").click(function () {
var value = $(".testClick").attr("href");
alert(value );
});
206089 次浏览

You're looking for $(this).attr("href");

this in your callback function refers to the clicked element.

   $(".addressClick").click(function () {
var addressValue = $(this).attr("href");
alert(addressValue );
});
$(".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.

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 this keyword instead of className (testClick)