简体   繁体   中英

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($(".link-??? 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.

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.

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());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM