【问题标题】:jquery getting values inside a ul li tag, but don't want a certain tagjquery在ul li标签中获取值,但不想要某个标签
【发布时间】:2012-06-08 05:30:07
【问题描述】:

我试图在 li 标记内获取文本值,但它有另一个我不想要的标记

示例:

<ul>
<li><a class="close">x</a>text</li>
<li><a class="close">x</a>more text</li>
<li><a class="close">x</a>wohoooo more text</li>
</ul>

我可以像这样得到标签

$("ul li").text();

但它也从a 捕获x。如何删除 a 标签?一定有一个我不熟悉的简单解决方案,

谢谢!

【问题讨论】:

    标签: jquery ajax text


    【解决方案1】:
    $("ul li").contents(':not(.close)').text()
    

    children() 不返回文本节点;要获取所有子节点,包括文本和评论节点,请使用 .contents() http://api.jquery.com/children/

    【讨论】:

      【解决方案2】:

      自定义伪类过滤器

      编写你自己的获取文本节点的表达式:

      $.extend( $.expr[":"], {
          textnodes: function( e ) {
              return e.nodeType === 3;
          }
      });
      
      $("ul li").contents(":textnodes");
      

      产生以下集合:

      ["text","more text","wohoooo more text"]
      

      小提琴:http://jsfiddle.net/jonathansampson/T3MQc/

      自定义方法

      您也可以扩展 jQuery.fn 以提供您自己的方法:

      $.extend( $.fn, {
          textnodes: function() {
              return $(this).contents().filter(function(){
                  return this.nodeType === 3;
              });
          }
      });
      
      $("ul li").textnodes();
      

      这会产生我们在上面看到的相同输出。

      小提琴:http://jsfiddle.net/jonathansampson/T3MQc/1/

      【讨论】:

      • 有趣的概念,谢谢。我会记下这一点。
      【解决方案3】:

      这很丑陋,但它有效。它克隆节点,然后删除所有子节点,最后打印剩下的文本:

      $('ul li').clone()
        .children()
          .remove()
          .end()
        .text()
      

      设法从这里喜欢的信息中提取更好的版本:How do I select text nodes with jQuery?

      $('ul li').contents().filter(function() {
          return this.nodeType == 3;
      }).text()
      

      【讨论】:

        【解决方案4】:
        $('ul li')
           .contents()   // target to contents of li
           .filter(function() {    
              return this.nodeType == 3;  // filtering over textnode
        }).text();  // get the text value
        

        DEMO

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-07-01
          • 2012-03-13
          • 1970-01-01
          • 2013-04-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多