设置选项"选择"从动态创建选项属性 [英] set option "selected" attribute from dynamic created option

查看:111
本文介绍了设置选项"选择"从动态创建选项属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使用javascript函数动态创建的选择选项。选择对象

I have a dynamic created select option using javascript function. the select object is

<select name="country" id="country">
</select>

在js函数执行时,该国对象

when the js function executed, the "country" object is

<select name="country" id="country">
    <option value="AF">Afghanistan</option>
    <option value="AL">Albania</option>
    ...
    <option value="ID">Indonesia</option>
    ...
    <option value="ZW">Zimbabwe</option>
</select>

和显示印尼作为默认选择的选项。注:没有选择=选择属性在该选项

and displaying "Indonesia" as default selected option. note : there is no selected="selected" attribute in that option.

然后我需要设置选择=选择属性印尼,我用这个

then I need to set selected="selected" attribute to "Indonesia", and I use this

var country = document.getElementById("country");
country.options[country.options.selectedIndex].setAttribute("selected", "selected");

使用Firebug

,我可以看到印尼选项是这样的。

using firebug, I can see the "Indonesia" option is like this

<option value="ID" selected="selected">Indonesia</option>

但它无法在IE浏览器(IE 8中测试)。

but it fail in IE (tested in IE 8).

然后我尝试使用jQuery

and then I tried using jQuery

$( function() {
    $("#country option:selected").attr("selected", "selected");
});

这无论是在FF和IE浏览器无法

it fail both in FF and IE

我需要的印尼选项必须选择=选择属性,所以当我点击重置按钮,它会选择印尼了。

I need the "Indonesia" option must have selected="selected" attribute so when I click reset button, it will select "Indonesia" again

改变js函数动态创建国家选项是不是选项。该解决方案必须在FF和IE浏览器都

changing js function to dynamic create "country" options is not the option. the solution must work both in FF and IE

感谢您

推荐答案

好问题。您将需要修改HTML本身,而不是依赖于DOM属性。

Good question. You will need to modify the HTML itself rather than rely on DOM properties.

var opt = $("option[val=ID]"),
    html = $("<div>").append(opt.clone()).html();
html = html.replace(/\>/, ' selected="selected">');
opt.replaceWith(html);

在code抓起选项元素印尼,克隆它,并把它变成一个新的div(文档不是)来检索完整的HTML字符串:&LT;期权价值=ID &GT;印尼及LT; /选项方式&gt;

然后,它确实一个字符串替换加选择=选择的作为一个字符串的属性,这一新的取代了原有的选项之前之一。

It then does a string replace to add the attribute selected="selected" as a string, before replacing the original option with this new one.

我测试了它在IE7。用复位按钮正常工作见这里: http://jsfiddle.net/XmW49/

I tested it on IE7. See it with the reset button working properly here: http://jsfiddle.net/XmW49/

这篇关于设置选项&QUOT;选择&QUOT;从动态创建选项属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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