2 laijianjia laijianjia 于 2013.05.28 17:18 提问

为什么下面JavaScript代码没有达到效果:根据当前星期改变标签<li>的背景颜色?
<html>
<head>
<title>ChangeColorWithDay</title>
<script language="JavaScript">
function focus()
{
    var liObjs = document.getElementByTagName("li");
    var today = (New Date()).getDay();
    for(var i = 0; i < liObjs.length; i++)
    {
        var liName = liObjs[i].getAttribute("name");
        if(("day" + today) == liName)
        {
            liObjs[i].style.background = "royalblue";
        }
    }
}
</script>
</head>

<body onload="focus()">

<li name="day0" style="background:tomato;">today is Sunday</li>
<li name="day1">today is Monday</li>
<li name="day2">today is Tuesday</li>
<li name="day3">today is Wednesday</li>
<li name="day4">today is Thursday</li>
<li name="day5">today is Friday</li>
<li name="day6">today is Saturday</li>

</body>
</html>

1个回答

franzhong
franzhong   2013.05.28 21:08
已采纳

改的地方两处:

1:var today = (New Date()).getDay();
//to
var today = (new Date()).getDay();

2:var liObjs = document.getElementByTagName("li");
//to
var liObjs = document.getElementsByTagName("li");
Csdn user default icon
上传中...
上传图片
插入图片