我有:
<li id="1">
This is what I want to get
<li id="2">
not needed to be selected
<li id = "3">
not needed...
</li>
</li>
</li>
我想用jQuery获取带有id = 1文本的li,这就是我所拥有的:
var id = "1"
var needed = $('li[id='+cat_id+']').text();
但这会得到所有文本,我只能获得This is what I want to get
。
更新
你是对的,这是错的,所以现在是:
<li id="1">
This is needed
<ul>
<li id = "2">Not needed</li>
<li id = "3"> Not needed too </li>
</ul>
</li>
在上面的示例中,我如何选择This is needed
,考虑到它的id =“1”?
答案 0 :(得分:4)
尝试:
var id = "1"
var needed = $('li[id=' + id + ']').clone().children().remove().end().text();
DEMO:http://jsfiddle.net/h397T/
编辑1
正如另一个人指出你的HTML是错的,它应该是:
<ul>
<li id="1">This is what I want to get
<ul>
<li id="2">not needed to be selected
<ul>
<li id="3">not needed...</li>
</ul>
</li>
</ul>
</li>
</ul>
但即便如此,我的解决方案仍有效,DEMO:http://jsfiddle.net/h397T/1/
编辑2
它仍适用于您更新的HTML,请参阅DEMO:http://jsfiddle.net/h397T/2/
答案 1 :(得分:3)
你的HTML不正确。应该是
<li id="1">
This is what I want to get
</li>
<li id="2">
not needed to be selected
</li>
<li id = "3">
not needed...
</li>
答案 2 :(得分:1)
如果你有像
这样的结构<ul>
<li></li>
<li></li>
<li></li>
</ul>
尝试
$("ul li").first();
答案 3 :(得分:0)
试试这个:
<强> HTML 强>
<ul>
<li id="1">This is what I want to get
<ul>
<li id="2">not needed to be selected</li>
<li id="3">not needed...</li>
</ul>
</li>
</ul>
<div id="result"></div>
<强>的jQuery 强>
var id = "#1"
var needed = $(id).children().detach();
$('#result').text($(id).text());
$(id).append(needed);
<强> Working fiddle 强>
答案 4 :(得分:-1)
试试这个
$('li:first').text();