如果我找到控件的方式如下,如何设置jQuery中下拉列表的索引:
$("*[id$='" + originalId + "']")
Run Code Online (Sandbox Code Playgroud)
我是这样做的,因为我正在动态创建控件,并且由于在使用Web窗体时更改了id,我发现这是一个解决方法,可以找到一些控件.但是一旦我有了jQuery对象,我就不知道如何将所选索引设置为0(零).
gna*_*arf 343
首先 - 选择器很慢.它将扫描每个寻找id的DOM元素.如果您可以为元素分配类,那么它将不会受到性能影响.
$(".myselect")
Run Code Online (Sandbox Code Playgroud)
要回答您的问题,有几种方法可以更改jQuery中的select元素值
// sets selected index of a select box to the option with the value "0"
$("select#elem").val('0');
// sets selected index of a select box to the option with the value ""
$("select#elem").val('');
// sets selected index to first item using the DOM
$("select#elem")[0].selectedIndex = 0;
// sets selected index to first item using jQuery (can work on multiple elements)
$("select#elem").prop('selectedIndex', 0);
Run Code Online (Sandbox Code Playgroud)
4im*_*ble 105
刚发现这个,它对我有用,我个人觉得它更容易阅读.
这将设置实际索引,就像gnarf的答案3号选项一样.
// sets selected index of a select box the actual index of 0
$("select#elem").attr('selectedIndex', 0);
Run Code Online (Sandbox Code Playgroud)
这本来不起作用,但现在确实...看错误:http: //dev.jquery.com/ticket/1474
根据评论中的建议使用:
$("select#elem").prop('selectedIndex', 0);
Pau*_*ulG 10
我在2015年写这个答案,由于某些原因(可能是旧版本的jQuery),其他答案都没有对我有用.我的意思是,他们更改了所选的索引,但实际上并没有反映实际的下拉列表.
这是另一种更改索引的方法,实际上它反映在下拉列表中:
$('#mydropdown').val('first').change();
Run Code Online (Sandbox Code Playgroud)
小智 9
JQuery代码:
$("#sel_status").prop('selectedIndex',1);
Run Code Online (Sandbox Code Playgroud)
Jsp代码:
Status:
<select name="sel_status"
id="sel_status">
<option value="1">-Status-</option>
<option>ALL</option>
<option>SENT</option>
<option>RECEIVED</option>
<option>DEACTIVE</option>
</select>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
467097 次 |
最近记录: |