刚看了个例子,有个地方没懂~代码如下
<script type="text/javascript"> var oList=document.getElementById("list"); var oLis=oList.getElementsByTagName("li"); for(var i=0;i<oLis.length;i++){ var oLi=oLis[i]; (i%2===0)?(oLi.className="a1",oLi.play="a1"):(oLi.className="a2",oLi.play="a2"); oLi.onmouseover=function () { this.className="a3"; } oLi.onmouseout=function(){ var oldVal=this.play; this.className=oldVal; //为什么不能写成 this.className=oLi.play? } } </script>
如果真按你那样写,你就会发现最后那个 oLi 会永远等于最后一个 <li> 元素(不明白这一点需要复习一下 JavaScript 基础知识)
oLi
<li>
但是,你可以写成 this.className = this.play。
this.className = this.play
至于这个例子里为什么不这么写,只是因为作者没这么写罢了。
真要讲究起来这里都不应该写循环,用 .forEach() 会更好一点。
.forEach()
1.4m articles
1.4m replys
5 comments
56.9k users