如何从函数中设置全局变量?
$(document).ready(function() {
var option = '';
$("[name=select_option_selected]").change(function() {
var option = $(this).val();
alert(option); // Example: Foo
});
alert(option); // Need it to alert Foo from the above change function
});
发布于 2011-04-06 02:34:30
在jQuery的作用域之外声明它
var option = '';
$(document).ready(function() {
$("[name=select_option_selected]").change(function() {
option = $(this).val();
alert(option); // Example: Foo
});
alert(option); //This will never be "Foo" since option isn't set until that select list changes
});
如果您想将其初始化为当前选定的值,请尝试执行以下操作:
var option = "";
var $select_option_selected = null;
$(function() {
$select_option_selected = $("[name='select_option_selected']")
$select_option_selected.change(function() {
option = $(this).val();
});
option = $select_option_selected.val();
});
发布于 2011-04-06 02:35:06
$(document).ready(function() {
var option = '';
$("[name=select_option_selected]").change(function() {
option = $(this).val(); //no declaration of new variable, JavaScript goes to what encloses the function
alert(option); // Example: Foo
});
alert(option); // Need it to alert Foo from the above change function
});
发布于 2011-04-06 02:34:50
你确定要这样做吗?通常要避免使用全局变量。在浏览器中,window
是全局对象,因此如果执行window.option = ...
,则option
将全局可用。
我强烈建议将全局变量命名为比"option“更独特的名称,以避免破坏现有的内容。
另一种选择,我也不推荐:不使用var
myvariable = 'foo';
如果myvariable以前从未被删除过,那么它将被声明为window上的一个属性,从而使其成为全局的。然而,这通常被认为是(非常)糟糕的做法。
https://stackoverflow.com/questions/5556699
复制相似问题