首页 > js,其中一行代码不懂其作用

js,其中一行代码不懂其作用

html<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>控制div属性</title>
        <style>
            #outer {
                width: 500px;
                margin: 0 auto;
                padding: 0;
                text-align: center;
            }
            #div1 {
                width: 100px;
                height: 100px;
                background: black;
                margin: 10px auto;
                display: block;
            }
        </style>
        <script>
            var changeStyle = function(elem, attr, value) {
                elem.style[attr] = value
            };
            window.onload = function() {
                var oBtn = document.getElementsByTagName("input");
                var oDiv = document.getElementById("div1");
                var oAtt = ["width", "height", "background", "display", "display"];
                var oVal = ["200px", "200px", "red", "none", "block"];
                for (var i = 0; i < oBtn.length; i++) {
                    oBtn[i].index = i;
                    oBtn[i].onclick = function() {
                        this.index == oBtn.length - 1 && (oDiv.style.cssText = "");//此行代码,不懂用意
                        changeStyle(oDiv, oAtt[this.index], oVal[this.index])
                    }
                }
            };
        </script>
    </head>

    <body>
        <div id="outer">
            <input type="button" value="变宽" />
            <input type="button" value="变高" />
            <input type="button" value="变色" />
            <input type="button" value="隐藏" />
            <input type="button" value="重置" />
            <div id="div1"></div>
        </div>
    </body>

</html>

我不明白那行代码是什么作用?把样式重置的原理是什么呢?谢谢了,本人js新人,不太懂


同楼上,等同于
if(this.index == oBtn.length - 1){ oDiv.style.cssText = ""; }

这里使用的是js的逻辑短路。例如:

1==1 && 2==1 && name='nick'

js会顺序执行逻辑判断语句,一直遇到表达式结果为false(这里2==1)或者结束为止,所以上例中的name没有被赋值

最经常出现的应用是用于兼容性的处理,例如:

var el = e.target || e.srcElement;


这是js逻辑与(&&)的范畴,例如:var a = b && c,如果b为真,则a=c;反之b为假,则a=b;即&&只看左边的真假,不看右边的结果 如果这懂了,下来看你的问题,你&&两边是js语句, 只看左边的话,就是判断,即楼上所说的if(this.index == oBtn.length - 1 ),判断真假,若为真就执行右边的语句,即oDiv.style.cssText = "",如果还不明白,就回复我


等同于:
if(this.index === oBtn.length-1){
oDiv.style.cssText = "" ;
}

【热门文章】
【热门文章】