jQuery UI滑块的最小/最大值存储到全局变量中

4

我对变量作用域的理解有困难,所以很难修复这个问题。我有一个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();
    }

  });

});

});

我该如何将最小值和最大值变量“全局化”,以便我可以在此函数外或其他地方使用它们?interval 与 console.log 可以作为一个示例,不用担心。通常,这是来自 jQuery UI 的滑块。

在文档准备就绪后定义它们:$(document).ready(function() { //在这里定义你的变量尝试一下并写下回复。 - Bob Swager
就像我说的,我对这些作用域的理解完全是新手级别,我正在努力学习,但目前还不太擅长。正如你所说,我已经尝试过了,但得到的输出是NaN。如果你能给我一些示例,那就太好了。 - Hiurako
在你的HTML中添加隐藏字段,并通过使用脚本来更新它们。 - Bob Swager
1个回答

0

如果你在函数内部声明min和max变量,它们只能在该函数内部使用。但是,如果你将它们声明在全局作用域(不在任何函数内部),你可以从任何地方访问它们。

当在函数内部更新全局变量时,不要使用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();
    }
    
  });
  
});

});
input { display: block; margin: 20px 0; }
<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()" />


再次感谢,但是当我尝试将console.log移到min和max值声明的上方时,输出为undefined。有什么想法吗? - Hiurako
是的,因为此时min和max只是声明了,但它们还没有任何值。我将更新代码,并将这些变量初始化为初始值。 - Chava Geldzahler
我已经更新了答案,以演示如何在全局范围内使用变量。 - Chava Geldzahler
我的最后一个问题是,我如何更新变量“live”,以便无需按下按钮即可更改它?我的意思是,我希望它能够在我移动滑块时自动更新。 :) - Hiurako
每当您移动滑块时,变量都会“实时”更新。 您不必按按钮更新变量,只需按按钮将值记录到控制台即可。 - Chava Geldzahler
让我们在聊天中继续这个讨论 - Chava Geldzahler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接