Rumah > Soal Jawab > teks badan
希望能用DOM的nextSibling属性设置<h1>元素相邻的下一个
元素的color样式,但是怎么整都没有效果,路过的大侠帮忙看一下,多谢!
<!DOCTYPE html">
<html>
<head>
<meta charset=utf-8" />
<script src="scripts/smm.js"></script>
</head>
<body>
<h1>Hold the front page</h1>
<p>This first paragraph leads you in.</p>
<p>Now you get the nitty-gritty of the story.</p>
<h1>Extra! Extra!</h1>
<p>Further developments are unfolding.</p>
<p>You can read all about it here.</p>
</body>
</html>
下面是对应的JavaScript代码...............................
function xx()
{ var e1=document.getElementsByTagName("h1");
for(var i=0;i<e1.length;i++)
{e2=nextElement(e1);
e2.style.color="red";}
}
function nextElement(node)
{ if(node.nextSibling.nodeType=1)
return node.nextSibling;
else
return nextElement(node.nextSibling);
return null;
}
window.onload=xx;
效果如下图:
PHP中文网2017-04-10 16:56:33
1.<meta charset=utf-8" />
少写了一个双引号
2.if(node.nextSibling.nodeType=1)
这里应该是双等号
3.
{ var e1=document.getElementsByTagName("h1");
for(var i=0;i<e1.length;i++)
{e2=nextElement(e1);//这里是循环,所以应该是e1[i]。e1是个对象集合,而不是单个dom节点,你的写法导致了nextElement(node)函数调用失败,因为这个函数的参数是一个dom节点
e2.style.color="red";}
}
PHP中文网2017-04-10 16:56:33
怎么写的这么复杂,这个明明就可以用css3选择器;
var h1s = document.getElementsByTagName("h1");
for (var i = 0, len = h1s.length; i < len; i++) {
var nextNode = h1s[i].nextSibling;
if (nextNode.nodeType !== 1) {
nextNode = nextNode.nextSibling;
}
nextNode.style.color = "red";
};