Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

js实现鼠标悬停背景色变化,其中鼠标移出时,为啥不能两个属性值赋值?

刚看了个例子,有个地方没懂~代码如下

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

如果真按你那样写,你就会发现最后那个 oLi 会永远等于最后一个 <li> 元素(不明白这一点需要复习一下 JavaScript 基础知识)

但是,你可以写成 this.className = this.play

至于这个例子里为什么不这么写,只是因为作者没这么写罢了。

真要讲究起来这里都不应该写循环,用 .forEach() 会更好一点。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...