这个JS代码 为什么加到另一个div的id里不起作用呢?
但是不知道为什么,复制多一份JS,getElementById()改为a2,a2起作用了,但a1的却不起作用了,
<script type="text/javascript">
window.onload = function(){
var divs = document.getElementById("a1").getElementsByTagName("li");
var len = divs.length;
for(var i=0;i<len;i++){
divs[i].onclick = function(){
for(var j=0;j<len;j++){
divs[j].style.backgroundColor = "";
}
this.style.backgroundColor = "rgb(65, 117, 252)";
};
}
};
</script>
请问是哪里出错了吗? 展开
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<title>last.html</title>
<style>
</style>
<script type="text/javascript">
var changeColor = function (id)
{
var div = document.getElementById (id);
div.index = -1;
var lis = div.getElementsByTagName ("li");
var len = lis.length;
for ( var i = 0; i < len; i++)
{
lis[i].index = i;
lis[i].onclick = function ()
{
if (div.index != -1)
{
lis[div.index].style.backgroundColor = "";
}
this.style.backgroundColor = "rgb(65, 117, 252)";
div.index = this.index;
};
}
}
onload = function ()
{
changeColor ("a1");
changeColor ("a2");
}
</script>
</head>
<body>
<div id="a1">
div1
<ul>
<li>dddddddddd</li>
<li>dddddddddd</li>
<li>dddddddddd</li>
</ul>
</div>
<div id="a2">
div2
<ul>
<li>ssssssssssss</li>
<li>ssssssssssss</li>
<li>ssssssssssss</li>
</ul>
</div>
</body>
</html>
window.onload = function(){……} 只能用一次,再次使用就会把上一次设定的处理函数顶掉。
<script type="text/javascript">
window.onload = function(){
var divs1 = document.getElementById("a1").getElementsByTagName("li");
var len1 = divs1.length;
for(var i=0;i<len1;i++){
divs[i].onclick = function(){
for(var j=0;j<len1;j++){
divs1[j].style.backgroundColor = "";
}
this.style.backgroundColor = "rgb(65, 117, 252)";
};
}
var divs2 = document.getElementById("a2").getElementsByTagName("li");
var len2 = divs2.length;
for(var i=0;i<len2;i++){
divs[i].onclick = function(){
for(var j=0;j<len2;j++){
divs2[j].style.backgroundColor = "";
}
this.style.backgroundColor = "rgb(65, 117, 252)";
};
}
};
</script>
另外,建议你学学用jQuery吧,好用地很!
可能是你公用了一个len导致的
<script type="text/javascript">
window.onload = function(){
setbc("a1");
setbc("a2");
}
function setbc(id){
var divs = document.getElementById(id).getElementsByTagName("li");
var len = divs.length;
for(var i=0;i<len;i++){
divs[i].onclick = function(){
for(var j=0;j<len;j++){
divs[j].style.backgroundColor = "";
}
this.style.backgroundColor = "rgb(65, 117, 252)";
};
}
}
</script>