【问题标题】:get text in div [duplicate]在div中获取文本[重复]
【发布时间】:2012-10-03 10:12:33
【问题描述】:

可能重复:
jquery - get text for element without children text

我有一个 div,里面有文本,在文本之后跨越如下:

<div>
text
<span>other text</span>
</div>

我只想在 div 中而不是在 span 中获取文本

谢谢

【问题讨论】:

  • 我要简短地说:我不明白。

标签: jquery


【解决方案1】:

试试这个

  var myText = $('#dd').clone()            
             .children()    //select all the children
             .remove()  //remove all the children
             .end() //again go back to selected element
             .text();   //get the text of element

【讨论】:

  • 赞成,我喜欢你的 .end() 快捷方式。
【解决方案2】:

你可以使用.clone(),像这样:

b = $('div').clone();
b.children('span').remove();
alert( b.text() ); // alerts "text"

使用.clone()我们可以复制一个div,去掉span,然后获取文本,这一切都不会影响页面上显示的原始DOM元素。

【讨论】:

    【解决方案3】:
    var theText = "";
    $('div').contents().each(function() {
        if(this.nodeType === 3) theText += $(this).text();
    });
    

    【讨论】:

    猜你喜欢
    • 2019-12-30
    • 1970-01-01
    • 2015-12-05
    • 2021-05-26
    • 1970-01-01
    • 2012-02-25
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多