javascript jQuery - 使用特定类从 <ul> 获取 <li>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19811167/
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 - get <li> from <ul> with a specific class
提问by John 'Mark' Smith
I have a list:
我有一个清单:
<ul id="list">
<li class="one">Item A</li>
<li class="one">Item B</li>
<li class="two">Item C</li>
<div id="pressed">Submit</div>
</ul>
and when "Submit" is pressed I want to retrieve the value of the list item which has a class of "two". In this instance, pressed Submit would return "Item C". Here's the jQuery I've tried:
当按下“提交”时,我想检索具有“二”类的列表项的值。在这种情况下,按下提交将返回“项目 C”。这是我尝试过的 jQuery:
$("#pressed").click(function() {
var v = $('#list').filter('.two').val();
alert(v);
});
But all this returns is 0
. What's the best way to do this? Only one <li>
will have a class of "two" at any one time.
但所有这些返回的是0
. 做到这一点的最佳方法是什么?<li>
任何时候只有一个人会有“二”类。
采纳答案by Adil
You need html() or text() instead of val(). The function val() is used for input elements like text, checkbox etc. Also put div outside ul to make your html valid as Rory McCrossan pointed
您需要 html() 或 text() 而不是 val()。函数 val() 用于输入元素,如文本、复选框等。同时将 div 放在 ul 之外以使您的 html 像 Rory McCrossan 指出的那样有效
var v = $('#list').filter('.two').html();
回答by Rory McCrossan
Firstly, your HTML is invalid as div
elements cannot be children of ul
:
首先,您的 HTML 无效,因为div
元素不能是以下元素的子元素ul
:
<ul id="list">
<li class="one">Item A</li>
<li class="one">Item B</li>
<li class="two">Item C</li>
</ul>
<div id="pressed">Submit</div>
Secondly, text()
is the property you want, not val()
:
其次,text()
是你想要的财产,而不是val()
:
$("#pressed").click(function() {
var v = $('#list').find('.two').text();
alert(v);
});
回答by Hossain Muctadir
After Rory McCrossan's correction with HTML you can do this.
在 Rory McCrossan 使用 HTML 进行更正后,您可以执行此操作。
$("#pressed").click(function() {
alert($('#list .two').text());
});