Javascript:将 HTML <select> 存储为变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17996523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:23:48  来源:igfitidea点击:

Javascript: Store HTML <select> as a variable?

javascripthtmlselectoptions

提问by user2642359

The HTML:

HTML:

      <select id="selected2">
          <option selected>1</option>
          <option>2</option>
          <option>3</option>
      </select>
      <select id="selected2">
          <option selected>1</option>
          <option>2</option>
          <option>3</option>
      </select>

I've tried using this code in JavaScript:

我曾尝试在 JavaScript 中使用此代码:

var dataCap = document.getElementById("selected2");

var userSelect = dataCap.options[dataCap.selectedIndex].text;

var dataCap = document.getElementById("selected2");

var userSelect = dataCap.options[dataCap.selectedIndex].text;

But console says: "TypeError: dataCap is null"

但控制台说:“TypeError:dataCap 为空”

回答by Jacques ジャック

You need the set a value for each option:

您需要为每个选项设置一个值:

<select id="selected2">
      <option selected value=""></option>
      <option value="2">2</option>
      <option value="3">3</option>
  </select>

The text between the tags is just for the user to see, but does not return the value.

标签之间的文字仅供用户查看,不返回值。

Also, your javascript variable should read:

此外,您的 javascript 变量应为:

var dataCap = document.getElementById("selected2").value;

I added .valueto the end so it knows to get the value.

我添加.value到最后,所以它知道获取值。