Answers:
首先-选择器非常慢。它将扫描每个DOM元素以查找ID。如果可以为元素分配一个类,则对性能的影响较小。
$(".myselect")
为了回答您的问题,有几种方法可以更改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);
#an-id
更快,但是*[id$=ends-with]
刚找到这个,它对我有用,我个人觉得它更容易阅读。
这将设置实际索引,就像gnarf的答案3选项一样。
// sets selected index of a select box the actual index of 0
$("select#elem").attr('selectedIndex', 0);
这以前不起作用,但现在可以了。参见错误:http : //dev.jquery.com/ticket/1474
根据评论中的建议使用:
$("select#elem").prop('selectedIndex', 0);
.prop('selectedIndex', 0);
无论是否.attr()
工作,都应该使用:)
我在2015年写了这个答案,由于某种原因(可能是jQuery的较旧版本),其他答案对我没有用。我的意思是,他们更改了所选索引,但实际上并没有反映实际的下拉列表。
这是更改索引的另一种方法,实际上可以将其反映在下拉列表中:
$('#mydropdown').val('first').change();
prop('selectedIndex', ...);
更改选择(通过Chrome和Firefox测试)没有问题。
change
在下拉菜单中触发事件,对于通过调用prop('selectedIndex', ...)
而不是来更改选择的人员,这也可能是有用的修复/解决方法val(...)
。也许问题出在,您正在听某个change
事件,那对您不起作用?的确,仅仅改变prop
选择第二个选项
$('#your-select-box-id :nth-child(2)').prop('selected', true);
在这里,我们添加`trigger('change')来触发事件。
$('#your-select-box-id :nth-child(2)').prop('selected', true).trigger('change');
$("[id$='" + originalId + "']").val("0 index value");
将其设置为0