How to get attribut with a class?
I have a question.
I have two links.
Example :
<.a href="/one.html" id="1" class="link" onclick="doSomething(id)">One<./a>
and
<.a href="/Two.html" id="2" class="link" onclick="doSo开发者_Go百科mething(id)">Two<./a>
I don't wanna use the attribute "onclick" to get the attribut id
.
I want to use $(".link").attr(id)
to get the attribut id
.
So my code is :
$(".link").click(function(){ alert($(this).attr(id)); })
The question is : How can we know WHICH link will be display ? 1
or 2
? And why ?
Thanks in advance.
You're missing the quotes round the name of the attribute you want.
$(".link").click(function(){
alert($(this).attr("id"));
});
live example: http://jsfiddle.net/nxQmH/
For your a links, you do not need to have the doSomething(id) bit - jquery will take care of this with the click function:
So you have:
<.a href="#" id="1" class="link">One<./.a>
and
<.a href="#" id="2" class="link">Two<./.a>
For your jquery function use:
$(document).ready(function() {
$("a.link").click(function(){ alert($(this).attr('id')); })
});
You were missing the quote marks around the id attribute.
If you use $(".link").attr("id")
, you will get the first one that the jQuery object returns. The jQuery object will work its way through the DOM starting at the beginning, so it will be 1.
For the click function, you should get the ID of this
, as if you had used plain JS's this.id
.
Note that to use .attr("id")
you need quotes around "id".
Also note that you are already setting a click handler with onclick="doSomething(id)"
. If you want to pass the ID of the link to onclick (not needed since you will have this.id
in the function), you can do doSomething(this.id)
.
Here's some test code for you.
Well if you look at your code the this
object is what will tell you which ID you are going to get. In the case of the .click()
method for jquery this
refers directly to the DOM object clicked. So if you do $(SOME_ID).click(function () { alert($(this).class() })
you will see the class of the DOM clicked.
If that is not coherent maybe this will be
http://remysharp.com/2007/04/12/jquerys-this-demystified/
The special variable "this" is bound at the time of the click event to whichever element was actually clicked. So, your code will show the id of the link that was clicked.
精彩评论