How can i know which class was selected via jQuery & JS
I have a list with links:
<li class="link-1"><a href="#">One</a></li>
<li class="link-2"><a href="#">Two</a></li>
<li class="link-3"><a href="#">Three</a></li>
..
user clicks on any link, then with jQuery I want to display the content of the link.. somthing like:
$(".link-??? a").click(function() {
alert($(".li开发者_JAVA百科nk-??? a").html());
})
something like this. I am not going to create X function (as the number of the links), so what can I do? I should replace the ???
in somtehing else..
You could do:
$('li[class^="link"] a').click(...
However this would only work if the li
have only one class or if the link-X
class is the first in the list.
Inside the handler you can use $(this)
to refer to the a
element:
alert($(this).text());
Much better would be to give the li
elements a common class:
<li class="link"><a href="#">One</a></li>
<li class="link"><a href="#">Two</a></li>
<li class="link"><a href="#">Three</a></li>
$('.link a').click(...
will be much more reliable.
Give each element the same class. Then in your javascript reference this within your function. Check out the link below to see a working example
http://jsfiddle.net/kprgr/2/
<li class="link"><a href="#">One</a></li>
<li class="link"><a href="#">Two</a></li>
<li class="link"><a href="#">Three</a></li>
$(".link").click(function() {
alert($(this).find("a").html());
});
Try..
$(".link-??? a").click(function() {
alert(this.innerHTML);
})
Inside the click event, this
should refer to the element that was clicked.
You could also do..
alert($(this).html());
..but the first way is simpler, and faster.
精彩评论