jQuery:查找包含嵌套ul的列表项的文本 [英] jQuery: Find the text of a list item that contains a nested ul
问题描述
我有以下内容:
<ul id="list">
<li>item1
<ul>
<li>sub1</li>
<li>sub2</li>
</ul>
</li>
</ul>
我想回复li点击事件,并在其他地方使用li的文本.但是,如果单击的是包含嵌套ul的li,那么我当然会得到所有元素的文本.
I'd like to respond to a li click event and use the text of the li elsewhere. However, if the click is on an li that contains a nested ul, I of course get the text of all elements.
$("#list li").click(function() {
alert($(this).text());
});
按预期返回item1sub1sub2.
returns item1sub1sub2, as expected.
如果单击项目1 li,我不知道如何获取"item1".我没有运气就尝试了以下方法:
I can't figure out how to get just 'item1' if the item 1 li is clicked. I tried the following (among other things) with no luck:
$("#list li").click(function() {
alert($(this).filter("ul").text());
});
有什么想法吗?
编辑
这是一个示例的片段-可能有多个层次.我也不想将列表项文本包装在跨度或其他标记中.
This is a snippet of an example - it could be multiple levels deep. I also do not want to wrap the list item text in a span or other markup.
推荐答案
这种方法呢?克隆对象,删除克隆的子对象,然后然后查找文本内容.
What about this approach? Clone the object, remove the clone's children and then find the text content.
$("#list li").click(function () {
alert($(this).clone().children().remove().end().text());
}
也许不是最有效的方法,但它是完全直观,整洁的,而且您不必弄乱html.
Perhaps not the most efficient approach, but it's entirely intuitive, pretty tidy, and you don't have to muck with your html.
这篇关于jQuery:查找包含嵌套ul的列表项的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!