【问题标题】:read only li tag and not everything else below in the DOM tree? [duplicate]只读 li 标签而不是 DOM 树中的所有其他标签? [复制]
【发布时间】:2013-08-21 09:01:06
【问题描述】:

我有这个列表项:

<li class="list">A <span class="kol">1</span></li>
<li class="list">B <span class="kol">1</span></li>
<li class="list">C <span class="kol">1</span></li>

我正在使用它来读取值:

$( ".list" ).each(function() {
    alert($(this).text()); //gives me A 1
    alert($(this).children().text()); //gives me 1
});

我只需要在第一个警报中获得 A 值。我怎样才能做到这一点?是否有任何 jQuery 方法,因此它不会读取 DOM 树中 li 标记下的所有内容?

【问题讨论】:

  • 不完全重复...

标签: jquery list dom each


【解决方案1】:

不确定直接的方法,但这是什么

$(".list").each(function () {
    console.log($(this).clone().find('span').remove().end().text()); //gives me A
    console.log($(this).children().text()); //gives me 1
});

【讨论】:

  • 正是我所需要的...之前没用过˙clone 所以点赞!谢谢
【解决方案2】:

.children()

.clone()

console.log($(this).clone().children('span').remove().end().text()); 

【讨论】:

    【解决方案3】:

    您可以从每个li.list's childNodes 中获取第一个nodeValue

    console.log(this.childNodes[0].nodeValue);
    

    Fiddle

    【讨论】:

      【解决方案4】:

      您可以将 firstChild 与数据一起使用

      $(".list").each(function(i, item) {
          alert(item.firstChild.data); 
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-20
        • 1970-01-01
        • 2020-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-06
        相关资源
        最近更新 更多