Javascript jQuery,找到li类名(在ul里面)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3604681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery, find li class name (inside ul)
提问by There Are Four Lights
I have ul with a number of li inside. All li have an id "#category" but different classes (like ".tools", ".milk", ".apple").
我有 ul 里面有很多 li。所有 li 都有一个 id“#category”,但有不同的类(如“.tools”、“.milk”、“.apple”)。
Using jQuery. I do :
使用 jQuery。我愿意 :
$("li#category").click(function(){ some_other_thing ( .... )});
now i have to put a li's class "name" — (a string indeed) inside the some_other_thing() function instead of ....
现在我必须在 some_other_thing() 函数中而不是 ....
How it can be done?
怎么做?
回答by Thinker
$(this).attr('class')
回答by Anurag
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.
ID 在文档中必须是唯一的,因此具有多个<li>具有 id 的元素"category"是无效的。将其更改为类或数据属性或其他内容。或者只是将一个类分配给父类,<ul>以便您可以轻松检索其中的所有 li。
<ul id="categories">
<li class="tools">
<li class="milk">
</ul>
Get all li's, and assign the click handler.
获取所有 li,并分配点击处理程序。
$('#categories li').click(function() {
var className = $(this).attr('class');
some_other_thing(className);
});
回答by Paul Lammertsma
Beware that idmust be unique! You're suggesting that each lielement has the same id. You might want to replace it with a class, e.g.:
请注意,它id必须是独一无二的!您建议每个li元素都具有相同的id. 您可能想用 a 替换它class,例如:
<ul>
<li class="category tools" />
<li class="category milk" />
</ul>
Then select with:
然后选择:
$('li.category').click(function(){});
回答by Morgan ARR Allen
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>
如果我理解正确,问题是您不能有多个具有相同 ID 的 li。每页只能有一个唯一 ID。您可能想要的是将 ID 更改为类。所以你会有一些类似的东西。
<ul>
<li class="category milK">Chocolate</li>
<li class="category tool">Big Hammer</li>
</ul>
Then you can search with $("li.category").click(function() {....});
然后你可以搜索 $("li.category").click(function() {....});
回答by Steve
Your li elements need to have unique IDs. Once they do, you can select all li children of the ul with the ">" operator:
您的 li 元素需要具有唯一 ID。完成后,您可以使用“>”运算符选择 ul 的所有 li 子项:
var ul_elem = $("#id_of_ul");
$("> li", ul_elem).click(...);
OR
或者
$("#id_of_ul > li").click(...);
OR
或者
$("ul.classname > li").click(...);

![Javascript 类型错误 [ERR_INVALID_ARG_TYPE]:“路径”参数必须是字符串类型。启动反应应用程序时引发的接收类型未定义](/res/img/loading.gif)