警报JS阵列选择

时间:2016-08-16 15:17:31

标签: javascript html arrays

我有一个带有选项的选项,我将其添加到数组中,并且当您单击按钮时我尝试提醒特定消息,但仅当选择了正确的数组[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");
    }
};

2 个答案:

答案 0 :(得分:4)

您无法比较这样的数组。您需要使用文字编号。 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');
  }
};

答案 1 :(得分:0)

如果我已正确理解您的问题,您需要选择的更新值:

button.onclick = function()
{
  if(document.getElementById("list").selectedIndex==1) // Also change = to ==
   {
   alert("hello");
   }
};

https://jsfiddle.net/6bs1vjva/1/