【问题标题】:How to select only text in a div containg other div in jQuery?如何仅选择 div 中的文本包含 jQuery 中的另一个 div?
【发布时间】:2013-10-18 22:22:31
【问题描述】:

我有这个代码:

<div class="bodytext1typeenc">Ce qu’il faut retenir
    <div class="al">Budget «solidarités».</div>
</div>

我只想获得“Ce qu'il faut retenir”。我试过这个:

$('.bodytext1typeenc').text() // --> doesn't work.
$('.bodytext1typeenc').remove('.al') //  --> doesn't work.

有什么帮助吗?谢谢!

【问题讨论】:

    标签: javascript jquery css jquery-selectors


    【解决方案1】:

    您可以克隆、删除子项并获取文本。见下文,

    var $clone = $('.bodytext1typeenc').clone();
    $clone.children().remove()
    $clone.text(); //should return the div's text
    

    注意:如果您不想保留原始内容,则无需克隆。

    演示: http://jsfiddle.net/PX2yA/

    【讨论】:

      【解决方案2】:

      嘿试试这个,你想做的是克隆你的元素然后删除你的子元素

      http://jsfiddle.net/HgdyG/

      $(".bodytext1typeenc")
              .clone()    //clone the element
              .children() //select all the children
              .remove()   //remove all the children
              .end()  //again go back to selected element
              .text();
      

      如果你经常使用这个,你可以创建一个像这样的简单扩展

      jQuery.fn.noChild= function() {
      
          return $(this).clone()
                  .children()
                  .remove()
                  .end()
                  .text();
      
      };
      

      然后运行

      $(".bodytext1typeenc").noChild();
      

      【讨论】:

      • 非常感谢!它工作得很好。我对您在 Stackoverflow 上的第一个问题的回答速度感到惊讶;-) 再次感谢!
      • 没问题,祝你的项目好运。不要忘记选择一个答案作为接受的答案
      【解决方案3】:

      您可以使用 contents() 并过滤掉 noteType TEXT_NODE (3)

      var val = $('.bodytext1typeenc').contents().filter(function() {
        return this.nodeType == 3;
      }).text();
      val = $.trim(val);
      
      alert('"' + val + '"'); // "Ce qu’il faut retenir"
      

      演示:http://jsbin.com/AsilIpo/1/

      【讨论】:

      • 它也可以,谢谢,但我不明白如何;-)
      • @FabienfromParis 我建议你阅读:api.jquery.com/contents 关于内容块,然后我们只需过滤掉所有与过滤方法匹配的集合(查看 nodeType 是否为 text_node)。
      猜你喜欢
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-01
      相关资源
      最近更新 更多