开发者

jQuery, find li class name (inside ul)

I have ul with a number of li inside. All li have an id "#category" but different classes (like ".tools", ".milk", ".apple").

Using jQuery. I do :

$("li#category").click(function(){ some_other_thing ( .... )});

now i have to put 开发者_如何学JAVAa li's class "name" — (a string indeed) inside the some_other_thing() function instead of ....

How it can be done?


$(this).attr('class')


Beware that id must be unique! You're suggesting that each li element has the same id. You might want to replace it with a class, e.g.:

<ul>
  <li class="category tools" />
  <li class="category milk" />
</ul>

Then select with:

$('li.category').click(function(){});


ID's have to be unique in a document, so having multiple <li> elements with the id "category" is invalid. Change that to a class or a data attribute or something else. Or just assign a class to the parent <ul> so you can easily retrieve all li's inside it.

<ul id="categories">
    <li class="tools">
    <li class="milk">
</ul>

Get all li's, and assign the click handler.

$('#categories li').click(function() {
    var className = $(this).attr('class');
    some_other_thing(className);
});


Your li elements need to have unique IDs. Once they do, you can select all li children of the ul with the ">" operator:

var ul_elem = $("#id_of_ul");
$("> li", ul_elem).click(...);

OR

$("#id_of_ul > li").click(...);

OR

$("ul.classname > li").click(...);


If I understand this correctly, the problem is that you cannot have multiple li's with the same ID. You can only have one unique ID per page. What you probably want is to change the ID to class. So you'd have something along these lines.
<ul>
<li class="category milK">Chocolate</li>
<li class="category tool">Big Hammer</li>
</ul>

Then you can search with $("li.category").click(function() {....});

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜