您好,我有两个问题,我从 jQuery UI 站点提取了这个脚本,这里是完整代码的链接 http://jqueryui.com/animate/
1) var = 状态的目的是什么?您可以在 if 语句中使用 bool 值 true 来代替吗?
2) 在 if/else 语句之后,您可以看到 var = !state。这样做的目的是什么以及有什么作用!意思是?
<script>
$(function() {
var state = true;
$( "#button" ).click(function() {
if ( state ) {
$( "#effect" ).animate({
backgroundColor: "#aa0000",
color: "#fff",
width: 500
}, 1000 );
} else {
$( "#effect" ).animate({
backgroundColor: "#fff",
color: "#000",
width: 240
}, 1000 );
}
state = !state;
});
});
</script>
最佳答案
JavaScript 中 bool 值的 not (!) 运算符会在 bool 值 true
和 false
之间切换状态,因此:
state = !state;
的效果是,如果 state 为 true,则现在为 false,反之亦然。回答你的第一个问题:
var state = true;
表示初始状态
从true开始。像 state
这样的 JavaScript 变量是可变的,并且 state 的值将根据上面的切换进行更改,该切换是由每次单击按钮触发的。
将所有内容放在一起,并添加注释:
// Set the initial visual state
var state = true;
// jQuery handler for each button click
$( "#button" ).click(function() {
if ( state ) {
// Visual effects when state is true
} else {
// Visual effects when state is false
}
// Now change the visual state, (which will be applied in the next click)
state = !state;
});
有趣的是,状态仅在应用新的视觉状态后才会更改,这意味着显示更新滞后
状态。
关于javascript - JavaScript中 "!"中的 `state = !state;`是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27436749/