如何在 jQuery Slider 函数中创建全局变量
我的脚本中有一个滑块:
var uniquePrice;
$( "#slider-secondary" ).slider({
range: "min",
value: 0,
min: 0,
max: 50,
slide: function( event, ui ) {
$( "#amount-secondary" ).val( ui.value );
uniquePrice = ui.value * 1500;
}
});
console.log(uniquePrice);
并且我需要在滑块函数之外的代码中进一步使用 uniquePrice var。它不起作用 - console.log(uniquePrice);说“未定义”。
我做错了什么?
PS 当然,我在函数之前定义了全局变量,抱歉忘记在这里包含。
I have a slider inside my script:
var uniquePrice;
$( "#slider-secondary" ).slider({
range: "min",
value: 0,
min: 0,
max: 50,
slide: function( event, ui ) {
$( "#amount-secondary" ).val( ui.value );
uniquePrice = ui.value * 1500;
}
});
console.log(uniquePrice);
And I need to use the uniquePrice var further in the code, outside of the slider function. And it doesn't work - console.log(uniquePrice); says "undefined".
What am I doing wrong?
P.S. Of course I defined the global variable before the function, sorry for forgetting to include here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须在函数外部定义变量。
如果您想要函数之外的变量,您可以执行以下操作:
编辑:将 console.log 添加到滑块函数
You have to define the variable outside of the function.
if you want the variable outside of the function you can do:
edit: added the console.log to the slider function
我想我在某处读到,如果您忘记将“var”放在变量名称前面,它将被声明为全局变量。请确认或否认这一点;)
PS 如果完全删除第 1 行会发生什么?你会得到什么样的错误?
I think I read somewhere that if you forget to put the 'var' infront of the name of the variable, it gets declared as a global variable. Please confirm or deny this ;)
P.S. What happens if you remove line #1 altogether? What kind of error do you get?
console.log() 将在该函数设置该变量之前被调用。 js 将:
因此,在滑动发生之前,该变量将是未定义的
The console.log() is going to be called before that variable is set by that function. The js will:
So until the slide happens that variable will be undefined