什么是“!” JavaScript中`state =!state;`中的均值

仿冒

您好,我有两个问题是我从jQuery UI网站提取了此脚本,这是完整代码的链接http://jqueryui.com/animate/

1)var = state的目的是什么?您可以在if语句中使用布尔值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中的not(!)运算符可在bool值true之间切换状态false,因此:

state = !state;

其结果是,如果状态为true,则现在为false,反之亦然。要回答您的第一个问题:

var state = true;

表示初始state从true开始。像这样的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;
});

有趣的是,仅在应用了新的视觉状态后才更改状态,这意味着显示器会更新lags状态。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章