码迷,mamicode.com
首页 > 其他好文 > 详细

DOM中文本节点索引方法

时间:2016-11-28 00:24:00      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:text   ext   original   http   java   with   next   amp   objects   

问题

对于 jquery 接口text()只能取到有标签的 dom对象中 文本内容。

如果索引对象本身就是文本节点,则不好索引到, 没有相关的索引选择器。

 

例如:

对于<input>aaa 形式的代码, $("input").next().text(), 则不能返回 aaa。

 

下面有讨论使用jquery索引的方法, 目标是在某个标签下, 找到所有 text node的 对象:

http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery

var getTextNodesIn = function(el) {
    return $(el).find(":not(iframe)").addBack().contents().filter(function() {
        return this.nodeType == 3;
    });
};

getTextNodesIn(el);

 

解决方法

期望使用dom原生api获取 text node值。

https://developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling

 

例如:

对于<input>aaa 形式的代码, $("input").get(0).nextSibling.nodeValue, 则不能返回 aaa。

 

注释:

对于返回的text内容, 浏览器往往会在前面带有空格, 在后面带有换行, 则使用 string.replace方法去除。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FString

 

originalstr = string.replace(str, /[\w]/g,  "")

 

trim接口也可以试试。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

DOM中文本节点索引方法

标签:text   ext   original   http   java   with   next   amp   objects   

原文地址:http://www.cnblogs.com/lightsong/p/6107355.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!