【发布时间】:2013-10-24 14:06:03
【问题描述】:
在"use strict" 应用程序中,我使用document.createTreeWalker 来遍历DOM 树。从浏览器获取树后,我使用 while 循环将值推送到数组中。该代码是对优秀的Letteringjs.com 插件的升级,我的版本可以在here 中看到。
function injector(t, splitter, klass, after) {
var inject = '', n,
tree = [],
styleStack = [],
splitIndex = 0,
styleAndSplit = function (node, splitter, klass, after) {
var particles = $(node).text().split(splitter);
// Wrap each particle with parent style tags if present
for (var j = 0, len = particles.length; j < len; j++) {
var str = '<span class="'+klass+((splitIndex++)+1)+'">'+particles[j]+'</span>'+after;
for (var k = styleStack.length - 1, style; style = styleStack[k--];) {
str = '<' + style.tagName.toLowerCase() + (style.className ? ' class="' + style.className + '"' : '') + '>' +
str +
'</' + style.tagName.toLowerCase() + '>'
}
inject += str;
}
},
Walker /* Texas Ranger */ = document.createTreeWalker(
t,
NodeFilter.SHOW_ALL,
{ acceptNode: function (node) {
// Keep only text nodes and style altering tags
if (node.nodeType === 3 || node.nodeType === 1 && !!node.tagName &&
(node.tagName.toLowerCase() === 'i' ||
node.tagName.toLowerCase() === 'b' ||
node.tagName.toLowerCase() === 'u' ||
node.tagName.toLowerCase() === 'span')) {
return NodeFilter.FILTER_ACCEPT;
} else {
return NodeFilter.FILTER_SKIP;
}
}},
false
);
while (n = Walker.nextNode()) tree.push(n);
// This loop traverses all of the nodes in the order they appear within the HTML tree
// It will then stack up nested styling tags accordingly
for (var i = 0, node; node = tree[i++];) {
if (node.nodeType === 1) {
styleStack.push(node);
} else {
// Get rid of nodes containing only whitespace (newlines specifically)
if ($.trim(node.nodeValue).length) {
while (styleStack.length && node.parentNode !== styleStack[styleStack.length - 1]) { styleStack.pop(); }
styleAndSplit(node, splitter, klass, after);
}
}
}
$(t).empty().append(inject);
}
此代码也适用于 Firefox、Chrome 和移动浏览器。但是 IE9 & IE10 玩的不太好。
两者都在while (n = Walker.nextNode()) tree.push(n); 行中断执行,提示:
SCRIPT1047:在严格模式下,函数声明不能嵌套 在语句或块中。它们可能只出现在顶层或 直接在函数体内。
编辑:这是example from MSDN 应该抛出这个错误:
var arr = [1, 2, 3, 4, 5];
var index = null;
for (index in arr) {
function myFunc() {};
}
编辑:但这没有意义,因为我没有声明一个函数,我只是在执行一个。尽管如此,我还是按照 fred02138 的建议删除了 styleAndSplit 函数声明(我只是用函数代码替换了调用,并删除了声明) - 但它并没有修复错误。。 p>
是否有其他方法可以遍历TreeWalker,或者是否有针对 IE 的解决方法(不丢失严格模式)?
【问题讨论】:
-
你能展示更多你的代码吗?
-
styleAndSplit呢?那不是嵌套函数声明吗? -
@fred02138 但这没有任何意义,因为我在我的应用程序的其他部分使用这种模式和
use-strict不会产生错误。更重要的是,它只发生在 IE 中。不过我会试一试。并让您知道。 -
@fred02138 它仍然在同一行中断并出现相同的错误。
-
@scunliffe 遇到这个错误只是为了找个借口在这里发表评论是值得的,但我仍然想要一个体面的解决方案;)
标签: javascript internet-explorer dom use-strict