使用jQuery设置Dropdown的选定索引 [英] Set the selected index of a Dropdown using jQuery
问题描述
如果我找到控件的方式如下,如何在jQuery中设置下拉列表的索引:
How do I set the index of a dropdown in jQuery if the way I'm finding the control is as follows:
$("*[id$='" + originalId + "']")
之所以这样做是因为我是动态创建控件的,并且由于使用Web Forms时ID会更改,因此我发现这是一种为我找到一些控件的方法.但是一旦有了jQuery对象,就不知道如何将所选索引设置为0(零).
I do it this way because I'm creating controls dynamically and since the ids are changed when using Web Forms, I found this as a work around to find me some controls. But once I have the jQuery object, I do not know how to set the selected index to 0 (zero).
推荐答案
首先-选择器非常慢.它将扫描每个DOM元素以查找ID.如果您可以为元素分配一个类,则对性能的影响较小.
First of all - that selector is pretty slow. It will scan every DOM element looking for the ids. It will be less of a performance hit if you can assign a class to the element.
$(".myselect")
尽管要回答您的问题,但是有几种方法可以更改jQuery中的select元素值
To answer your question though, there are a few ways to change the select elements value in jQuery
// 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);
这篇关于使用jQuery设置Dropdown的选定索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!