我对变量范围理解有困难,所以我很难解决这个问题。我有js脚本,看起来像这样:
<div id="slider"></div>
$(document).ready(function() {
$(function(){
var update = function() {
var min = $("#slider").slider("values")[0];
var max = $("#slider").slider("values")[1];
var i = setInterval(function() {
console.log("Hi");
}, min + Math.random() * max);
return i;
}
var i;
$("#slider").slider({
values: [1000, 1750],
min: 500,
max: 3900,
step: 0.1,
slide: function (e, ui) {
clearInterval(i);
i = update();
}
});
});
});
如何让min和max变量“全局”,我可以在这个函数或其他地方使用它们?使用console.log的间隔可以是一个例子,不用担心。通常,这是来自jQuery UI的滑块。
答案 0 :(得分:0)
如果在函数中声明最小和最大变量,它们仅在该函数中可用。但是,如果在全局范围内(在任何函数之外)声明它们,则可以从任何位置访问它们。
从函数中更新全局变量时,请勿使用var
关键字:
myVariable = myValue; // without var keyword, this variable refers to global myVariable (or wherever it is first found in the scope chain. If not found, it will create a new variable in current scope.)
如果您使用var
关键字,则会在当前范围内创建一个新变量。
var myVariable = myValue; // this creates a new variable myVariable in the current scope
// Declare variables in the global scope
var min = 50;
var max = 200;
var update = function() {
// Update the global variable - do not use var keyword
min = $("#slider").slider("values")[0];
max = $("#slider").slider("values")[1];
}
// Logs the global min/max variables
var logValues = function() {
console.log("Min = " + min + ", Max = " + max);
}
$(document).ready(function() {
$(function(){
$("#slider").slider({
values: [50, 200],
min: 5,
max: 390,
step: 0.1,
slide: function (e, ui) {
update();
}
});
});
});
&#13;
input { display: block; margin: 20px 0; }
&#13;
<link href="https://code.jquery.com/ui/1.9.1/themes/black-tie/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<div id="slider"></div>
<p>Moving the slider updates min and max variables to the current selected values.</p><p> Click the button to log the current value (taken from global variables).
<input type="button" value="Get Current Values" onclick="logValues()" />
&#13;