DOM中文本节点索引方法

问题

对于 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

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