jQuery的next()的本地JavaScript替代方法

3

I have this code:

$.each(this.items, function(key, item) {
    item = $(item);
    item.css('background', 'red');
    item.next().css('display', 'none');
}

现在,我需要使用纯JavaScript重写它,所以我正在这样做

document.getElementById(aItems[iCount].id).style.background = 'red';
document.getElementById(aItems[iCount].id).style.display = 'none';

问题在于必须对next()项设置display:none,而不是这一个,我该怎么办?谢谢。

3个回答

12

试试这个:

item.nextSibling.style.display = 'none'

请记住 nextSibling 可能选择元素旁边的文本内容, 所以你可能需要使用:
item.nextSibling.nextSibling.style.display = 'none'

另一个选择是使用Bergi建议的nextElementSibling。但是,这在所有浏览器中都不被支持。不过,你可以自己创建该函数:
function nextElementSibling(element) {
    do { 
        element = element.nextSibling;
    } while (element && element.nodeType !== 1);
    return element;
}

在这种情况下:
nextElementSibling(item).style.display = 'none';

最后但并非最不重要的,如果你想用本地JS替换jQuery的$.each()方法,我建议先看看Palash的回答


3
请注意,此操作将考虑所有节点类型,因此如果第一个元素后面有文本节点(或注释、其他非元素节点),则可能会得到意外的结果。nextElementSibling是正确的工具,但不幸的是并非在所有地方都受支持。 - Frédéric Hamidi
2
@FrédéricHamidi:添加了一个选择。 - Cerbrus
能否请给我点踩的人解释一下原因?如果我犯了错误,我想从中学习。 - Cerbrus

2
你可以使用所选 DOM 节点的 nextElementSibling 属性
var item = document.getElementById(aItems[iCount].id);
item.style.background = 'red';
item.style.display = 'none';
if (item.nextElementSibling)
    item.nextElementSibling.style.display = 'none';

2
你也可以尝试这个:
for(var iCount = 0; iCount < aItems.length;i++)
{
     var current = aItems[iCount].id;
     var next = aItems[iCount + 1].id;
     if ( next != null ) {
          document.getElementById(current).style.background = 'red';
          document.getElementById(next).style.display = 'none';
     }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接