Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

jquery - Save variables globally from radio input

Having the following htmt and function. I can't get var skinColor to save "light" or "dark" after i click my button. How do i need to define the so when i select a radio button it saves the var globally ? I get a skinColor not defined error , but that is the point , i'm trying to defined 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;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your problem here is the scope, you can find information about what the scope is here: https://www.w3schools.com/js/js_scope.asp

but in short, when you declare a variable inside a function, it is not accessible globally, you can access it only on that same function. If you want to access it from outside, you will need to declare it before; Example:

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

or you can use the global object, for chrome for example you can access it through the "window" object, but this is not recommended.

Example

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...