Setting a global variable and accessing it in jqueryjavascript - Stack Overflow

I'm having problems creating a global variable and resetting it through jquery. here is my codevar

I'm having problems creating a global variable and resetting it through jquery. here is my code

var x = 1;
$(document).ready(function () {
    $("#button").click(function () {
        if(x === 1) {
            alert("test1");
            var x = 2;
        } else if(x === 2) {
            alert("test2");
            var x = 3;
        } else {
            alert("test 3");
        }
    });
});

I want to be able to click the same button three times and have all the tests appear, but instead it goes straight to the last option "test 3". I apologize if this is a silly question, but I'm a bit new to jquery and javascript.

I'm having problems creating a global variable and resetting it through jquery. here is my code

var x = 1;
$(document).ready(function () {
    $("#button").click(function () {
        if(x === 1) {
            alert("test1");
            var x = 2;
        } else if(x === 2) {
            alert("test2");
            var x = 3;
        } else {
            alert("test 3");
        }
    });
});

I want to be able to click the same button three times and have all the tests appear, but instead it goes straight to the last option "test 3". I apologize if this is a silly question, but I'm a bit new to jquery and javascript.

Share Improve this question edited Mar 28, 2013 at 2:25 Derek 朕會功夫 94.5k45 gold badges198 silver badges253 bronze badges asked Mar 28, 2013 at 1:48 AndrewAndrew 552 silver badges6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

Just remove the var from the variable assignment inside the click event callback. The var makes the variable local to that scope/closure.

 if (x === 1) {
      alert("test1");
      x = 2;
  }
  else if (x === 2) {
      alert("test2");
      x = 3;
  }
  else {
      alert("test 3");
  }

As a side point the very first var is not necessary, var x = 1 and x = 1 does the same thing when the code is not in a closure/function. All they are doing is assigning window.x = 1.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745164055a4614537.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信