2017-07-17 64 views
4

我对变量作用域的理解有困难,所以我很难解决这个问题。我有js脚本,看起来像:jQuery UI滑块最小/最大值到全局变量

<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(); 
    } 

    }); 

}); 

}); 

如何实际上使最小和最大变量“全球性”,我可以用他们出这个功能,或者别的地方? console.log间隔可以是一个例子,不用担心。通常,这是来自jQuery UI的滑块。

+0

文件准备好后,它们定义: '$(文件)。就绪(函数(){//你的变量去here' 试试吧,写一个答复 –

+0

正如我所说的完全禁用这些范围的理解,我正在努力,但迄今为止我并不擅长,正如你所说,我已经尝试过,但得到了NaN的输出,所以如果你可以给我一些例子,这将是好的。 – Hatchling

+0

添加隐藏den字段放入您的html中,并使用您的脚本更新它们。 –

回答

0

如果您声明函数中的最小和最大变量,它们仅在该函数中可用。但是,如果您在全局范围(在任何函数之外)声明它们,则可以从任何地方访问它们。

当从一个函数中更新一个全局变量,不要使用var关键字:如果您使用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 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()" />

+0

再次感谢,但是当我尝试移动上面的console.log,其中声明了最小值和最大值时,我得到了未定义的输出。任何想法? – Hatchling

+0

是的,因为在那一点上,最小和最大值只被声明,但他们没有任何价值。我将更新代码,并将这些变量初始化为初始值。 –

+0

我已经更新了答案,以演示如何在全局范围内使用变量。 –

相关问题