如何获得对单击的超链接的引用

时间:2010-01-05 20:39:09

标签: jquery

我知道我可以在超链接元素上使用.click()方法。但是我怎么知道点击了哪个元素?首先,我必须参考超链接的ID。

所以我想在视图源中有一个像这样的超链接页面:

<a href="addButton1" href="...someurl"><img src="somebutton"></a>
<a href="addButton2" href="...someurl"><img src="somebutton"></a>
<a href="addButton3" href="...someurl"><img src="somebutton"></a>
<a href="addButton4" href="...someurl"><img src="somebutton"></a>

当用户点击addButton1时,我怎么知道它首先被点击的addButton1,以便我现在可以在其上应用.click()事件?

2 个答案:

答案 0 :(得分:5)

观察页面上所有链接的点击事件:

$("a").click(function (e) { 
      // this function fires anytime a hyperlink is clicked

      e.preventDefault();

      // reference $(this) to get at the specific 
      // link that fired the event, such as:
      alert($(this).attr('href')); // display href value of the hyperlink
    });

观察页面上链接子集的点击事件:

在超链接标记中添加一个类。示例:<a class="observe" href="#">

并将上述功能事件签名更改为:

$("a.observe").click(function (e) { ... });

答案 1 :(得分:0)

区分链接的最佳方法是向其添加类或ID。然后你可以像这样设置事件处理:

HTML:

<a href="javascript:" class="myClass" id="myId">Click here!</a>

jQuery可以在两种方式中完成(好的,有两种以上,但这里有两种)方式:

$('#myId').click(function() { doSomething() });
$('.myClass').click(function() { doSomething() });