Javascript 使用 jQuery 设置 <option> 元素的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5380704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:57:08  来源:igfitidea点击:

Setting the text of an <option> element using jQuery

javascriptjqueryhtmlselect

提问by Toby

Using jQuery what is the best way of editing option text for a given select value.

使用 jQuery 编辑给定选择值的选项文本的最佳方式是什么。

I know the value of the option I want to edit. I thought it would be something like...

我知道要编辑的选项的值。我以为它会是这样的......

$('#select').val().$('option').html('New Text');

But I am clearly missing something.

但我显然错过了一些东西。

回答by Anurag

$('#select option[value="someValue"]').text("newText")

could use .htmlinstead of .text, if adding html content.

如果添加 html 内容,可以使用.html代替.text, 。

回答by kieran

Something like this?

像这样的东西?

$('#select').children('option').text('New Text');

Have a look at Selectorsfor more information on selecting the correct item. You could do something like

有关选择正确项目的更多信息,请查看选择器。你可以做类似的事情

$('#select').children('option:first').text('New Text');

Or you can use

或者你可以使用

$('#select').children('option[value="thevalue"]').text('New Text');

If you know the value.

如果你知道它的价值。

回答by Frédéric Hamidi

You're probably looking for the :selectedselector and the text()method:

您可能正在寻找:selected选择器和text()方法:

$("#select option:selected").text("New Text");

回答by varadha

This one help you to get the options value,

这个可以帮助您获得选项值,

$('#select_id').children('option[value="thevalue"]').text('New Text');

And you can set default selected value by using prop()function. Take an example here.

您可以使用prop()功能设置默认选择值。在这里举个例子。