gpt4 book ai didi

javascript - 如何从函数内设置全局变量

转载 作者:行者123 更新时间:2023-12-03 21:53:16 25 4
gpt4 key购买 nike

如何在函数内设置全局变量?

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

最佳答案

在 jQuery onready 范围之外声明它

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

关于javascript - 如何从函数内设置全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5556699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com