0

我有:

<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” ,我该如何选择?

4

5 回答 5

4

尝试:

var id = "1"
var needed = $('li[id=' + id + ']').clone().children().remove().end().text();

演示: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>

但即便如此,我的解决方案仍然有效,演示:http: //jsfiddle.net/h397T/1/

编辑 2

它仍然适用于您更新的 HTML,请参阅演示:http: //jsfiddle.net/h397T/2/

于 2013-02-26T09:36:58.350 回答
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>
于 2013-02-26T09:36:41.310 回答
1

如果你有这样的结构

<ul>
 <li></li>
 <li></li>
 <li></li>
</ul>

尝试

$("ul li").first();
于 2013-02-26T09:37:19.157 回答
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);

工作小提琴

于 2013-02-26T09:51:06.900 回答
-1

试试这个

$('li:first').text();
于 2013-02-26T09:36:22.497 回答