我读过一些关于如何使用 jQuery 在 HTML Select 元素中选择第一个选项的文章,但我似乎无法让它在 jQuery 移动页面上工作。
选择元素:
<select id="myList">
<option value="" selected>Select a List</option>
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>
我调用脚本来选择第一个选项:
$("#myList").val($("#myList option:first").val());
我并不是试图获取选择元素中第一个选项的值,我实际上是试图选择它。
为了让它在 jQuery 移动页面上运行,我还需要做些什么吗?
谢谢。
最佳答案
一种解决方案是使用selectmenu("refresh")
。
refresh update the custom select: This is used to update the custom select to reflect the native select element's value. If the number of options in the select are different than the number of items in the custom menu, it'll rebuild the custom menu. Also, if you pass a true argument you can force the rebuild to happen.
//refresh value
$('select').selectmenu('refresh');
//refresh and force rebuild
$('select').selectmenu('refresh', true);
html
<select id="myList">
<option value="" selected>Select a List</option>
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>
js
$("#myList").val($("#myList option:eq(1)").val());
$("#myList").selectmenu("refresh");
关于jquery - 使用 jQuery 选择选择元素中的第一个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26961272/