简体   繁体   English

jQuery - 得到 <li> 从 <ul> 与特定的类

[英]jQuery - get <li> from <ul> with a specific class

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". 在这种情况下,按下提交将返回“项目C”。 Here's the jQuery I've tried: 这是我尝试过的jQuery:

$("#pressed").click(function() {
   var v = $('#list').filter('.two').val();
   alert(v);
});

But all this returns is 0 . 但所有这些回报都是0 What's the best way to do this? 最好的方法是什么? Only one <li> will have a class of "two" at any one time. 任何时候只有一个<li>会有一个“两个”类。

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

Example fiddle 示例小提琴

You need html() or text() instead of val(). 你需要html()或text()而不是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 函数val()用于输入元素,如文本,复选框等。还将div放在ul之外,使你的html有效,因为Rory McCrossan指出

Live Demo 现场演示

var v = $('#list').filter('.two').html();

After Rory McCrossan's correction with HTML you can do this. 在Rory McCrossan用HTML修正之后你可以做到这一点。

$("#pressed").click(function() {
   alert($('#list .two').text());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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