警告JS数组选择

Alerting JS Array Selection

本文关键字:选择 数组 JS 警告      更新时间:2023-09-26

我有一个选择的选项,我放入一个数组,我试图提醒一个特定的消息,当你点击一个按钮,但只有当正确的数组[x]已被选中。但是,当我单击按钮时,无论选项是什么,我都会收到消息。我做错了什么?

代码:

HTML:

<button id="button">Click Me</button>
<br />
<br />
<select id = "list" value = "list">
   <option id="one" value="one">
   one
   </option>
   <option id="two" value="two">
   two
   </option>
   <option id="three" value="three">
   three
   </option>
</select>

JS:

var listArr = [];
var button = document.getElementById("button");
var list = document.getElementById("list");
var selected = document.getElementById("list").selectedIndex;
for (var i = 0; i < list.options.length; i++) {
    listArr[i] = list.options[i].value;
}
button.onclick = function() {
    if (selected = [1]) {
        alert("hello");
    }
};

不能这样比较数组。您需要使用文字数字代替。JSFiddle

var listArr = [];
var button = document.getElementById("button");
var list = document.getElementById("list");
var selected = document.getElementById("list");
for(var i = 0; i < list.options.length; i++) {
  listArr[i] = list.options[i].value;
}
button.onclick = function() {
  if(selected.selectedIndex == 1) {
    alert('hello');
  }
};

如果我正确理解了您的问题,您需要select:

的更新值。
button.onclick = function()
{
  if(document.getElementById("list").selectedIndex==1) // Also change = to ==
   {
   alert("hello");
   }
};
https://jsfiddle.net/6bs1vjva/1/