如何在jquery中获取文本节点的html?
我将其用作我的语言翻译 jquery 脚本中的众多部分之一。
当我循环浏览网页上的所有节点时,这部分抓取节点的文本。
然而,它也抓住了很多隐藏的 JavaScript 作为文本节点。
那么有没有办法修改它,只获取 html 端呢?并加上修剪不需要的空白?
这是原始代码。
var content = function (node, txt) {
if (txt) {
if (node.textContent) {
node.textContent = txt;
} else if (node.nodeValue) {
node.nodeValue = txt;
}
} else {
return node.textContent ? node.textContent : node.nodeValue;
}
};
这里将帮助展示这段代码的上下文。
// recursive tree walker
(function (parent) {
var childs = parent.childNodes;
// if childs object has data
if (childs && childs.length) {
var i = childs.length; while (i--) {
// assign node variable to childs object
node = childs[i];
// text node found, do the replacement
if (node.nodeType == 3) {
// assign the current value to a variable
var value = content(node);
} else {
arguments.callee(node);
}
}
}
})(document.body);
所有这些都是我的语言翻译代码的工作逻辑,我只是想调整输入,以便它获取文本,但页面源代码中没有 JavaScript 代码。
I use this as 1 of the many parts in my language translation jquery script.
This part grab's the text of a node, as I loop through all the nodes on a web page.
However it grab's a lot of the hidden javascript as a text node as well.
So is there a way to modify this, to just get the html side? And plus trim unneeded whitespace?
Here is the original code.
var content = function (node, txt) {
if (txt) {
if (node.textContent) {
node.textContent = txt;
} else if (node.nodeValue) {
node.nodeValue = txt;
}
} else {
return node.textContent ? node.textContent : node.nodeValue;
}
};
Here will help show the context of this code.
// recursive tree walker
(function (parent) {
var childs = parent.childNodes;
// if childs object has data
if (childs && childs.length) {
var i = childs.length; while (i--) {
// assign node variable to childs object
node = childs[i];
// text node found, do the replacement
if (node.nodeType == 3) {
// assign the current value to a variable
var value = content(node);
} else {
arguments.callee(node);
}
}
}
})(document.body);
All of this is the logic my language translation code works, I just want to tweak the input so it grabs the text but no javascript code that is in the source of the page.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不太确定您发布的函数是从哪里调用的(您如何使用它)。不过,请查看 这个问题,它的作用类似于您想要的。关键是:
这就是检查 DOM 节点是否为文本节点的方法。除此之外,您可能必须专门处理脚本标签,但您可以:
在 jquery 选择器中删除它们
Not quite sure where the function you've posted is being called from (how you're using it). Checkout this question though, which does something like what you want. The key is:
That's how you check if the DOM node is a text node. Beyond that, you may have to handle script tags specially, but you could:
in your jquery selector to get rid of them