简体   繁体   English

如何在jQuery中更改下拉列表项?

[英]How to change a dropdownlist item in jQuery?

I have a drop down list for asp.net. 我有一个asp.net的下拉列表。 I need to change the text of one item. 我需要更改一项的文本。 The list is loaded with a table in a database. 该列表在数据库中加载了表格。 Because of a weird weird accessibility situation, the only way I can get this task done is through js. 由于存在一种奇怪的可访问性问题,我只能通过js来完成此任务。

Here is a sample drop down: 这是一个示例下拉列表:

<asp:DropDownList ID="myDrop" runat="server" onselectedindexchanged="myDrop_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>

Here are the in-HTML items: 这是HTML中的项目:

<option value="1">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>

and so on. 等等。 Thanks! 谢谢!

you can use jquery to change the text of option using jquery filters to change 1st option text you can use ':eq(0)' and for second ':eq(1)' and so on 您可以使用jquery更改选项文本,使用jquery过滤器 更改第一个选项文本,可以使用':eq(0)',第二个可以使用':eq(1)',依此类推。

$("#myDrop>option:eq(0)").text('myName'); 

if you are not sure with the indexing of option the following approach can be used 如果不确定选项的索引编制,可以使用以下方法

var Arr = $('#myDrop>option');
$.each(Arr,function(i,data){
if($(data).attr('value') == "2"){
$(data).text("changetext")
}
})

Not sure if this is what you meant. 不知道这是否是您的意思。 Hope it helps. 希望能帮助到你。

https://jsfiddle.net/5oed5wrh/ https://jsfiddle.net/5oed5wrh/

var ddl = document.getElementById('myDrop');
var index = 1;
ddl.options[index].innerText = "Something new";

I dont know which option you are trying to change so I just picked the middle one. 我不知道您要更改哪个选项,所以我只选择了中间一个。 If you are trying to change all of them, you can do so with a simple loop. 如果您要更改所有这些内容,则可以通过简单的循环进行更改。

Also, if you are using jQuery you can use .text() instead of innerText. 另外,如果您使用的是jQuery,则可以使用.text()代替innerText。 I believe innerText is a IE construct. 我相信innerText是IE构造。 It will help if you have cross-browser compatibility concerns. 如果您有跨浏览器兼容性问题,这将有所帮助。

var ddl = document.getElementById('myDrop');
var index = 1;
$(ddl.options[index]).text("Something new");

As you've specifically asked for a solution using jQuery: 正如您专门要求使用jQuery的解决方案:

$('#myDrop option[value="2"]').text("new text")

Select the option that you want to edit and then amend the text inside it. 选择您要编辑的选项,然后修改其中的文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM