【发布时间】:2013-09-25 19:29:43
【问题描述】:
我想动态修改选择元素的选定索引。有时,选择中的选项会导致其他选择中的选项被禁用。我可以在运行时在更改时很好地禁用选项,但我无法更改选择显示的选项。
例如,如果我有这个选择:
<select>
<option>Even or Odd?</option>
<option>Even</option>
<option>Odd</option>
</select>
<select>
<option value="">Pick a Number</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option
</select>
When "Odd" is selected, the even numbers will be disabled, but if an even number was already selected when the first select was changed to "Odd" then even though the selected index for the second select is now 0, the显示的值还是原来的值。
我目前已经尝试过:
selects[i].selectedIndex = 0;
selects[i].value = "Pick a Number";
$(selects[i]).val("Pick a Number");
$(selects[i]).attrs("selectedIndex", 0);
最多会发生的是所选索引会发生变化,或者元素的值会变成空字符串,而不会真正改变页面上显示的内容。
【问题讨论】:
-
方法的名称是
attr而不是attrs。 -
不仅如此,而且 attr 是错误的函数。根据下面的答案,道具是正确的。
-
selects[i].selectedIndex = 0应该可以工作。
标签: javascript jquery dom