JQuery在选择列表上设置选定的属性 [英] JQuery setting the selected attribute on a select list

查看:93
本文介绍了JQuery在选择列表上设置选定的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下html

 < select id =dropdown> 
< option> A< / option>
< option> B< / option>
< option> C< / option>
< / select>

我有字符串B,所以我想设置所选的attrribute,所以它会:

 < select id =dropdown> 
< option> A< / option>
< option selected =selected> B< / option>
< option> C< / option>
< / select>

我如何在JQuery中做到这一点?

值属性,您可以显着减少代码需要做到这一点:

 < option> B< / option> 

 < option value =B> B< / option> 

当您想要做类似的事情时,这会很有帮助:

 < option value =IL>伊利诺伊< / option> 

因此,下面的jQuery将进行更改:

  $(select option [value ='B'])。attr(selected,selected); 

如果您决定包含使用 value 属性,您将被要求遍历每个选项,并手动检查其值:

 <$ c $ ($(this).text()==B)
$(this).attr(selected)。 ,selected);
});


I have the following html

<select id="dropdown">
    <option>A</option>
    <option>B</option>
    <option>C</option>
</select>

I have the string "B" so I want to set the selected attrribute on it so it will be:

<select id="dropdown">
    <option>A</option>
    <option selected="selected">B</option>
    <option>C</option>
</select>

How would I do this in JQuery?

解决方案

If you don't mind modifying your HTML a little to include the value attribute of the options, you can significantly reduce the code necessary to do this:

<option>B</option>

to

<option value="B">B</option>

This will be helpful when you want to do something like:

<option value="IL">Illinois</option>

With that, the follow jQuery will make the change:

$("select option[value='B']").attr("selected","selected");

If you decide not to include the use of the value attribute, you will be required to cycle through each option, and manually check its value:

$("select option").each(function(){
  if ($(this).text() == "B")
    $(this).attr("selected","selected");
});

这篇关于JQuery在选择列表上设置选定的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆