全局保存来自无线电输入的变量



具有以下htmt和函数。我无法获取var skinColor来保存";"轻";或";深色";在我点击按钮之后。我需要如何定义so?当我选择一个单选按钮时,它会全局保存var?我得到了一个skinColor未定义的错误,但这就是重点,我正在尝试定义skinColor。

<input type="radio" id="load_lightskin" name="skin" value="light_skin">
<label for="light_skin">Light Skin</label>
<input type="radio" id="load_darkskin" name="skin" value="dark_skin">
<label for="dark_skin">Dark Skin</label>
<input id="InstallerSettings" type="button" onclick="SkinSettings()" value="Continue Install">
function SkinSettings(){
switch ($('input[name="skin"]:checked').val()){
case "light_skin":
var skinColor = "light";
load_template();
break;
case "dark_skin":
var skinColor = "dark";
load_template();
break;
default: 
alert("You must select a skin to continue."); 
break;
}
}

您的问题是作用域,您可以在这里找到有关作用域的信息:https://www.w3schools.com/js/js_scope.asp

但简而言之,当您在函数内部声明一个变量时,它是不可全局访问的,您只能在同一个函数上访问它。如果你想从外部访问它,你需要在之前声明它;示例:

let thisVariableIsGlobal = "hello world!";
(function yourFunctionName(){
let thisVariableIsLocal = "Quick test";
// You can edit thisVariableIsGlobal here and it will be applied globally, but don't redefine it using the var, let, or const keywords! 
})()
console.log(thisVariableIsGlobal ) // Return hello world!
console.log(thisVariableIsLocal ) // Return undefined

或者你可以使用全局对象,例如chrome,你可以通过";窗口";对象,但不建议这样做。

示例

(function yourFunctionName(){
window['thisVariableIsGlobal'] = 'Hello world';
})()
console.log(thisVariableIsGlobal ) // Return hello world!

最新更新