javascript 如何使用 Jquery 更改选项值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3269030/
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-10-25 00:41:55  来源:igfitidea点击:

How to change option value with Jquery?

javascriptjqueryoption

提问by karim79

I am looking for a way to change the option value from a select tag when users click on a link.

我正在寻找一种方法来在用户单击链接时从选择标记更改选项值。

For example I have a select option html:

例如,我有一个选择选项 html:

<select> <option value="0">Please Select</option> 
<option value="1">red</option> 
<option value="2">white</option> 
</select>

And I have 2 links <a href="#" title="red" class="preview_link">red</a> <a href="#" title="white">white</a>When user clicks red the option will switch to red and white will switch to white. I am using the following code but it is not working.

我有 2 个链接<a href="#" title="red" class="preview_link">red</a> <a href="#" title="white">white</a>当用户单击红色时,该选项将切换为红色,白色将切换为白色。我正在使用以下代码,但它不起作用。

 jQuery("a.preview_link").click(function() {
    var title = jQuery(this).attr("title");
        jQuery(this).parent('p').children("select :selected").text(title);
 });

Any suggestions?

有什么建议?

回答by karim79

Your way will set the option's text to the title attribute. Try:

您的方式将选项的文本设置为标题属性。尝试:

 jQuery("a.preview_link").click(function() {
    var title = jQuery(this).attr("title");
    jQuery(this).parent('p').find("select option").filter(function() {
        return $(this).text() == title;
    }).attr('selected', 'selected');
 });

See filter.

filter

回答by Brad Heller

Hmm, you're going about this wrong: Instead of changing the text of the selected option you need to loop over the <option/>elements and select the appropriate one, something like this:

嗯,你这样做是错误的:你需要循环<option/>元素并选择适当的元素,而不是更改所选选项的文本,如下所示:

$("select option").each(function() { 
    if($(this).text() == "red")) {
        this.selected = true; 
    }
});

Edit: There might be a select()function in jQuery. If that's the case then use that over the DOM property.

编辑:select()jQuery 中可能有一个函数。如果是这种情况,那么在 DOM 属性上使用它。

回答by TJ Koblentz

This?

这?

$("select #some-option").attr("selected", "selected");

Or this?

或这个?

$("select").val(index);