单击时获取最后一个值

时间:2016-05-04 09:24:31

标签: jquery

我创建了一个带初始值的字符串变量。每次我点击一个按钮,这个值都会改变。我创建了一个不同的按钮来获取变量的最后一个值,但每次单击它都会返回初始值。

如何获取变量的最后一个值?

<button id='button1'>button1</button>
<button id='button2'>button2</button>
<button id='buttonSpecific'>buttonSpecific</button>
<script>
    var varState = "Initial value" ;

    $("#button1").click(function() {
        var varState = "button1" ;
        console.log(varState)
    });

    $("#button2").click(function() {
        var varState = "button2" ;
        console.log(varState)
    });

    $("#buttonSpecific").click(function() {   
        // Get the last value 
        console.log(varState)
    });
</script>

2 个答案:

答案 0 :(得分:2)

&#13;
&#13;
var varState = "Initial value";

$("#button1").click(function() {
  varState = "button1"; //dont initialize again remove var
});
$("#button2").click(function() {
  varState = "button2"; //dont initialize again remove var
});
$("#buttonSpecific").click(function() {
  // Get the last value 
  console.log(varState)
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='button1'>button1</button>
<button id='button2'>button2</button>
<button id='buttonSpecific'>button3</button>
&#13;
&#13;
&#13;

不要再次初始化变量

答案 1 :(得分:1)

在每次点击事件中,你再次初始化变量,这就是为什么会出现这个问题,要将变量声明为全局,你只需要在所有脚本之上解析变量。

<button id='button1'>Button 1</button>
<button id='button2'>Button 2</button>
<button id='buttonSpecific'>Button Specific</button>

<script>
var varState = "Initial value" ;

$("#button1").click(function() {
  varState = "button1" ;
});
$("#button2").click(function() {
   varState = "button2" ;
});

$("#buttonSpecific").click(function() {   
  console.log(varState)
});
</script>