【问题标题】:jquery - get text for element without children textjquery - 获取没有子文本的元素的文本
【发布时间】:2012-07-06 21:44:01
【问题描述】:

例如我们有这个文件

<div id="mydiv">
    some text here 
    <div id="inner div">
         text for inner div
    </div>
</div>

我只需要使用如下代码获取#mydiv 文本:

alert($('#mydiv').text());  // will alert "some text here"

【问题讨论】:

  • 所以你想要所有个子文本节点,没有更深嵌套的文本节点?

标签: javascript jquery


【解决方案1】:

嘿,请试试这个”:http://jsfiddle.net/MtVxx/2/

这里为您的具体案例提供了很好的链接:http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/(这只会获取元素的文本)

希望这会有所帮助,:)

代码

jQuery.fn.justtext = function() {

    return $(this).clone()
            .children()
            .remove()
            .end()
            .text();

};

alert($('#mydiv').justtext());​

【讨论】:

  • +1 用于使用 .end()。从来不知道它存在,现在它非常有用。
  • @Grinn saweet bruv,是的,有一些 jq api,使用起来很棒,但没有被广泛使用,:) 很有趣,谢谢加 1。
  • 这似乎在 Win XP IE 8 中崩溃,clonechildren 周围的东西仍在试图解决这个问题..
【解决方案2】:

目前的accepted answer在性能方面非常糟糕,所以我觉得有义务写一个更轻量级的:

$.fn.mytext = function() {
    var str = '';

    this.contents().each(function() {
        if (this.nodeType == 3) {
            str += this.textContent || this.innerText || '';
        }
    });

    return str;
};

console.log($('#mydiv').mytext());​

【讨论】:

  • 好多了!我正在寻找一种方法来遍历选定元素的每个子元素,但我不知道 contents(),谢谢!
【解决方案3】:

类似于Ja͢ck's answer,但不需要显式迭代(通过.each())和收集textContents:

$('#mydiv').contents().filter(function(){return this.nodeType === 3}).text()

或者,如果您可以使用 箭头函数:

$('#mydiv').contents().filter((i, el) => el.nodeType === 3).text()

【讨论】:

    猜你喜欢
    • 2015-03-09
    • 2016-02-29
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多