我可能真的把事情复杂化了......而且很难解释,所以我在这里只显示代码:
for (var i = 0; i < x.length; i++) {
(function(i) {
if (x[i].className === 'RU') {
x[i].style.display = 'none';
if (x[i].previousSibling.tagName === 'BR' && x[i].previousSibling.style.display != 'none') {
x[i].previousSibling.style.display = 'none';
}
}
})(i);
}
这工作正常,但我想做的是在循环内创建一个函数,该函数将检查每个x[i].previousSibling
是否属于"BR"类型。 所以我需要声明一个函数,该函数将循环自身,直到它到达不是"BR"标签的元素。 我试过了:
for (var i = 0; i < x.length; i++) {
(function(i) {
if (x[i].className === 'RU') {
x[i].style.display = 'none';
var check = true;
var a = '';
function foo() {
while (check) {
if (x[i].previousSibling.tagName === 'BR' && x[i].previousSibling.style.display != 'none') {
x[i].previousSibling.style.display = 'none';
a = x[i].previousSibling;
}else
check = false;
foo();
}
}
}
})(i);
}
这什么也没做...我认为它甚至没有进入foo
功能。 有什么建议吗?
以下是经过一些调整并摆脱不必要的变量后有效的方法:
for (var i = 0; i < x.length; i++) {
(function(i) {
if (x[i].className === 'RU') {
x[i].style.display = 'none';
var a = x[i];
foo();
function foo() {
if (a.previousSibling && a.previousSibling.tagName === 'BR' && x[i].previousSibling.style.display != 'none') {
x[i].previousSibling.style.display = 'none';
a = a.previousSibling;
foo();
}
}
}
})(i);
}