<!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. Why do we need logical operations?
2.What is the relationship between this.index and op.style.cssText? Can you briefly explain it?
某草草2017-07-05 11:02:28
That sentence means: If the button clicked is "Reset", then the cssText
of the p1
element will be cleared. That is, the initial state of the p1
element is reset (without the style
value).
&&
Operations are performed from left to right, and the expression on the right is executed only when the expression on the left is true. Here, when this.index == oBtn.length - 1
, that is, when the last button is clicked, execute op.style.cssText = ""
.
This kind of writing is not worth promoting. It has poor readability and is not a good way of writing. The normal way to write it is:
if(this.index === oBtn.length - 1) {
op.style.cssText = ""
}
this.index
saves the serial number of the button and is used to determine which button was clicked. It cannot be expressed directly with i
. This is a famous flaw in JavaScript.
为情所困2017-07-05 11:02:28
this.index == oBtn.length - 1 && (op.style.cssText = "");
means: if it is the last btn, execute the following code (op.style.cssText = "")
, that is, clear the style
a==b&&code...
Equivalent to if(a==b){code....}
Personally I don’t like this way of writing.
2.What is the relationship between this.index and op.style.cssText
this.index is the serial number of the buttonop.style.cssText = ""
means clearing the op style.