javascript - js, gibt es ein paar Codezeilen, die Sie nicht verstehen?
女神的闺蜜爱上我
女神的闺蜜爱上我 2017-07-05 11:00:28
0
2
777
<!Doctype html>
<html lang="en>
    <head>
        <meta http-equiv="Content-Type" content="text/html;            charset=utf-8" />
        <title>控制p属性</title>
        
        <script>
            var changeStyle = function(elem, attr, value) {
                elem.style[attr] = value
            };
            window.onload = function() {
                var oBtn = document.getElementsByTagName("input");
                var op = document.getElementById("p1");
                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 && (op.style.cssText = "");
                        changeStyle(op, oAtt[this.index], oVal[this.index])
                    }
                }
            };
        </script>
    </head>

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

1. Warum brauchen wir logische Operationen?
2. Welche Beziehung besteht zwischen this.index und op.style.cssText? Können Sie das kurz erklären?

女神的闺蜜爱上我
女神的闺蜜爱上我

Antworte allen(2)
某草草

那句的意思是:如果点击的按钮是“重置”,则把 p1 元素的 cssText 清空。也就是重置了 p1 元素的初始状态(没有 style 值)。

&& 运算是从左向右执行的,只有当左边表达式为真时,才执行右边的表达式。在这里既当 this.index == oBtn.length - 1,也就是点击的是最后一个按钮时,执行 op.style.cssText = ""

这种写法不值得提倡,阅读性很差,不是一个好的写法。正常的写法是:

if(this.index === oBtn.length - 1) {
  op.style.cssText = ""
}

this.index 就是保存了按钮的序号,用于判断点击的是哪个按钮。在这里不能直接用 i 来表示,这是 JavaScript 一个著名的缺陷。

为情所困
this.index == oBtn.length - 1 && (op.style.cssText = "");

表示:如果是最后一个btn的话,就执行后面的代码(op.style.cssText = ""),即清除样式

a==b&&code...

相当于if(a==b){code....}

个人不太喜欢这种写法。

2.this.index 与 op.style.cssText之间是怎么样的关系

this.index 是按钮的序号
op.style.cssText = ""表示清除op的样式。

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!