警告JS数组选择
Alerting JS Array Selection
我有一个选择的选项,我放入一个数组,我试图提醒一个特定的消息,当你点击一个按钮,但只有当正确的数组[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/相关文章:
- 如何在javascript中使用click函数选择数组元素
- 如何根据下拉选择来选择数组的第一列
- 如何在加号运算符之后选择数组元素的一部分
- 如何选择数组中的第一个对象(当 array[0] 不起作用时)
- jQuery:如何获取选择数组中元素的索引
- 选择数组的随机元素来设置Youtube视频ID API
- 使用计数器更改选择数组名称
- AngularJs 帮助,在传递给隔离范围的对象中选择数组时遇到问题
- PHP 从“选择 - 数组”字段中填充文本框
- 在 jsrender 中选择数组的一部分
- JavaScript 如何使用 NOT 的索引与选择数组
- 如何随机选择数组
- 对象数组-选择数组子集,其中对象属性为值数组
- 未选择数组中的最后一项
- Jquery 选择数组中括号之间的文本
- (如何)除了math.random随机选择的一个元素外,我可以选择数组中的所有元素吗
- 从Javascript对象中选择数组
- 如何通过每次单击来选择数组的新索引
- 如何有效地随机选择数组项而不重复
- 如何只选择数组中的特定值