gpt4 book ai didi

javascript - 检索 JS 变量

转载 作者:行者123 更新时间:2023-12-03 12:37:57 24 4
gpt4 key购买 nike

$('#lobSelect').change(function () {
var selectedLob = $('#mainWrapper').find('select[name="lob-select"] option:selected').val();
console.log(selectedLob); //prints to the console
});

console.log(selectedLob); //not available here

在上面的代码中,我使用变量 selectedLob 来存储从下拉列表中选择的值。

如何从函数外部检索该值?

另外说这个函数存储在 file1.js 中 - 我如何从不同文件夹中的 file2.js 访问这个变量。

谢谢

最佳答案

声明变量时,您将其设置为声明它的函数范围的本地变量。

在函数外部声明它:

var selectedLob;

并且不要在内部重新声明它:

$('#lobSelect').change(function () {
selectedLob = $('#mainWrapper').find('select[name="lob-select"] option:selected').val();
console.log(selectedLob); //prints to the console
});

这里仍然是未定义的:

console.log(selectedLob); //not available here

因为在更改事件触发之前它不会获得分配的值,但在该事件发生后它将可以在更广泛的范围内访问。

关于javascript - 检索 JS 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23654389/

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