我想根据点击设置变量,然后根据另一次点击增加相同的变量。
$("#set-1").click(function() {
var x = 1;
});
$("#set-2").click(function() {
var x = 2;
});
$("#set-3").click(function() {
var x = 3;
});
//...
$("#increment").click(function() {
x = x + 1;
});
但是当我点击#increment
时,不再定义x
。我怎样才能使它保持定义,即使在它定义的函数之外?
答案 0 :(得分:4)
只需在外面宣布:
var x;
$("#set-1").click(function() {
x = 1;
});
$("#set-2").click(function() {
x = 2;
});
$("#set-3").click(function() {
x = 3;
});
$("#increment").click(function() {
++x;
});
var x;
$("#set-1").click(function() {
x = 1;
});
$("#set-2").click(function() {
x = 2;
});
$("#set-3").click(function() {
x = 3;
});
$("#increment").click(function() {
++x;
});
$('body').click(function() {
$('#x').text(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="set-1">Set x=1</button>
<button id="set-2">Set x=2</button>
<button id="set-3">Set x=3</button>
<button id="increment">Increment x</button>
<p>x = <span id="x">undefined</span></p>
考虑统一事件处理程序:
$('[id ^= "set-"').click(function() {
x = +this.id.substr(4);
});
var x;
$('[id ^= "set-"').click(function() {
x = +this.id.substr(4);
});
$("#increment").click(function() {
++x;
});
$('body').click(function() {
$('#x').text(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="set-1">Set x=1</button>
<button id="set-2">Set x=2</button>
<button id="set-3">Set x=3</button>
<button id="increment">Increment x</button>
<p>x = <span id="x">undefined</span></p>