【发布时间】:2017-06-07 21:19:41
【问题描述】:
我需要一个选择元素的选项根据另一个元素的值来改变。
<select id="first">
<option value="1">one</option> // When you click this one, all the values of #second change (arbitrary number of entries)
<option value="2">two</option> // When you click this one, all the values of #second change to something else (not necessarily the same number)
</select>
<select id="second">
<option value="thisChanges">soDoesThis</option>
<option value="thisToo">andThis</option>
</select>
<script>
$("#first").on("change", function() {
<pseudo>
if #first == "1"
#second = {"this", "that", "the other"}
else if #first == "2"
#second = {"more", "even more", "yet another", "still more"}
</pseudo>
}
</script>
这几乎就是我所追求的(我花了数年时间才弄清楚如何完全替换选择框的值),但是按钮单击事件甚至不起作用。一分钟前它还在工作,虽然 for 循环没有。
显然,对于我的用例,我会检查是否单击了选择并使用.val() 检索其值,但我认为此按钮更易于调试。
HTML:
<select id="sel">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button>
Click me
</button>
JS:
var list = ['11', 'Eleven', '12', 'Twelve', '13', 'Thirteen'];
$('button').on('click', function () {
alert('click');
var sel = $('#sel');
alert('1');
sel.empty();
alert('2');
for (i = 0, i < list.length; i+2) {
$('#sel').append('<option value="' + list[i] + '">' + list[i+1] + '</option>');
}
alert('3');
});
【问题讨论】:
-
喜欢this ?
-
根据您的第一个元素,第二个元素的预期输出是什么?
标签: javascript jquery html asp.net-mvc