如何使用jQuery选择元素的自己的文本 [英] How to select own text of the element using jQuery

查看:76
本文介绍了如何使用jQuery选择元素的自己的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下html:

I have the following html:

<div>
    <div id="t1">Text1</div> 
    <div id="t2">
        Text2 
        <ul id="t3">
            <li id="t4">Text3</li>
        </ul>
    </div>
</div>

我想为每个元素选择 only own 文本。我尝试使用jQuery text 函数,但它返回所有元素的合并文本内容:

I want to select only own text for each element. I tried to use jQuery text function, but it returns the combined text content of all elements in selection:

t1 => Text1
t2 => Text2 Text3
t3 => Text3
t4 => Text3

我需要:

And what I need:

t1 => Text1
t2 => Text2
t3 =>
t4 => Text3 


推荐答案

$.fn.ownText = function() {
    return this.eq(0).contents().filter(function() {
       return this.nodeType === 3 // && $.trim(this.nodeValue).length;
    }).map(function() {
       return this.nodeValue;
    }).get().join('');
}

var text = $('#t2').ownText();

http://jsfiddle.net/5L9Ww/

一个稍快的选择:

A slightly faster alternative:

$.fn.ownText = function() {
    var children = this.get(0).childNodes, 
        l = children.length,
        a = [];
    for (var i = 0; i < l; i++) {
      if (children[i].nodeType === 3) 
          a.push(children[i].nodeValue);
    }
    return a.join('');
}

或者接受用于加入节点值的粘合剂的另一种方法,以修剪结果:

Or a different method that accepts a glue for joining the node's values and an option for trimming the result:

$.fn.ownText = function(o) {
    var opt = $.extend({ glue: "", trim: false }, o),
        children = this.get(0).childNodes, 
        l = children.length,
        a = [];
    for (var i = 0; i < l; i++) {
        if (children[i].nodeType === 3) {
          var val = children[i].nodeValue;
          a.push(opt.trim ? $.trim(val) : val);
        }
    }
    return a.join(opt.glue);
}

$('#t2').ownText({
    glue: ',',
    trim: true
});

这篇关于如何使用jQuery选择元素的自己的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆