首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >"!“在JavaScript中表示为‘state=!state;’

"!“在JavaScript中表示为‘state=!state;’
EN

Stack Overflow用户
提问于 2014-12-12 04:14:24
回答 4查看 414关注 0票数 0

你好,我从jQuery UI站点中提取了这个脚本,下面是指向完整代码http://jqueryui.com/animate/的链接

1) var = state的目的是什么?你能用if语句中的布尔值true代替吗?

2)在if/ var语句之后,您可以看到var= !state。这是什么目的和什么是!卑劣?

代码语言:javascript
复制
<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>
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-12-12 04:16:05

不(!)布尔值上的javascript运算符切换bool值truefalse之间的状态,因此:

代码语言:javascript
复制
state = !state;

其效果是,如果state为true,则它现在为false,反之亦然。要回答你的第一个问题:

代码语言:javascript
复制
var state = true;

这意味着初始的state从true开始。像state这样的Javascript变量是可变的,状态的值将按照上面的切换进行更改,这是通过单击一个按钮来触发的。

把它放在一起,并附上评论:

代码语言:javascript
复制
// 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状态。

票数 3
EN

Stack Overflow用户

发布于 2014-12-12 04:15:57

意思是“不”。如果是x = !false,则x为真。如果是x = !true,那么x是假的。

票数 3
EN

Stack Overflow用户

发布于 2014-12-12 04:30:21

它只是“不”的意思。下面是您使用它的几个例子:

代码语言:javascript
复制
function check() {

  if (!document.getElementById('text').value) {
    // if the input is empty, (NOT have a value) then alert the user
    alert('You did not enter text.');
  }
}
代码语言:javascript
复制
<input type="text" id="text" />
<button onclick="check()">Check if the input is emtpy.</button>

代码语言:javascript
复制
function check(){
  
  if (document.getElementById('number').value != 22){
    // != is the opposite of ==
    alert('Yay!  You didn\'t pick number 22!');
    }
  
  }
代码语言:javascript
复制
Please don't enter the number 22:
<input type="number" id="number" />
<button onclick="check()">Check number</button>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27436749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档