当有人单击选项时如何分配变量? (HTML)

How do I assign a variable when someone clicks an option? (HTML)

我一直在想办法让当有人点击一个选项时,一个变量被分配。这是我尝试过的:

function changessw() {
  switch (document.getElementById("ssw").value) {
    case "1":
      var test = "Im A";
      break;
    case "2":
      var test = "Im B";
      break;

  }
}
document.write(test)
<select name="ssw" id="ssw" onchange="changessw()">
  <option value="1">A</option>
  <option value="2">B</option>
</select>

该变量只有在我在函数中对其进行测试时才有效。我想在全球范围内工作。如有任何帮助,我们将不胜感激!

在函数外声明变量,然后在函数内赋值。

这是 link javascript https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript and the MDN 条目中关于范围的一篇文章 let

let test;

function changessw() {
  switch (document.getElementById("ssw").value) {
    case "1":
      test = "Im A";
      break;
    case "2":
      test = "Im B";
      break;

  }
}

function logTest() {
  console.log(test);
}
<select name="ssw" id="ssw" onchange="changessw()">
  <option value="1">A</option>
  <option value="2">B</option>
</select>
<button onclick="logTest()">Log test</button>

将您的变量声明移到函数范围之外。

var test;
function changessw() {
  switch (document.getElementById("ssw").value) {
    case "1":
      test = "Im A";
      break;
    case "2":
      test = "Im B";
      break;

  }
  console.log(test);
}
<select name="ssw" id="ssw" onchange="changessw()">
  <option value="1">A</option>
  <option value="2">B</option>
</select>

您可以在函数外声明变量 test 并在函数本身内赋值。

 var test ="";
function changessw() {
  switch (document.getElementById("ssw").value) {
    case "1":
      test = "Im A";
      console.log(test);
      break;
    case "2":
       test = "Im B";
      console.log(test);
      break;

  }
}
<select name="ssw" id="ssw" onchange="changessw()">
  <option value="1">A</option>
  <option value="2">B</option>
</select>