How to gain reference to a clicked Hyperlink
I understand that I can use the .click() method on a hyperlink element. But how开发者_StackOverflow中文版 do I know which element was clicked? First I have to gain reference to the hyperlink's ID.
So lets say I have a page of hyperlinks like this in view source:
<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>
when a user clicks addButton1, how do I even know it's addButton1 that was clicked in the first place so that I can now apply a .click() event on it?
To observe click event for all links on a page:
$("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
});
To observe click events for a subset of links on a page:
Add a class to your hyperlink tags. Example: <a class="observe" href="#">
And change the above function event signature to:
$("a.observe").click(function (e) { ... });
The best way to differentiate between links is to add a class or id to them. Then you can set event handling like so:
HTML:
<a href="javascript:" class="myClass" id="myId">Click here!</a>
jQuery can be done in one of two (ok, there are more than two, but here are two) ways:
$('#myId').click(function() { doSomething() });
$('.myClass').click(function() { doSomething() });
精彩评论