Vya*_*lav 17 html javascript jquery html-select
请解释我如何更改选项的"选定"属性?例如:
<select id="lang_select">
<option value="en" selected="selected">english</option>
<option value="ar">???????</option>
<option value="az">az?rbaycanl?</option>
<option value="bg">?????????</option>
<option value="ca">català</option>
<option value="cs">?eský</option>
<!-- some data cut -->
</select>
Run Code Online (Sandbox Code Playgroud)
因此,如果我更改下拉列表值,则html-data中没有任何更改.为什么?
只有当我尝试使用jQuery强制重新加载属性时才有效.
$(document).on('change',"select",function(){
var i = $(this)[0].selectedIndex;
var ch = $(this).children().each(function(index){
$(this).prop('selected',index == i);
if (index == i) {
$(this).attr('selected','selected');
} else {
$(this).removeAttr('selected');
}
});
});
Run Code Online (Sandbox Code Playgroud)
为什么?我怎么能避免这个?是否可以使用纯HTML更改"已选择"?
编辑 我想在html标签中这个属性因为我需要在将来保存和恢复这个html代码的一部分.
gue*_*314 16
更新,取代.attr("selected", true)
对.prop("selected", true)
注意,selected
属性的值返回true
或false
不"selected"
.
尝试使用selector $("option[value=" + this.value + "]", this)
,set property selected
to true
,.siblings()
删除未选中的selected
属性option
$(document).on("change","select",function(){
$("option[value=" + this.value + "]", this)
.attr("selected", true).siblings()
.removeAttr("selected")
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="lang_select">
<option value="en" selected="true">english</option>
<option value="ar">???????</option>
<option value="az">az?rbaycanl?</option>
<option value="bg">?????????</option>
<option value="ca">català</option>
<option value="cs">?eský</option>
<!-- some data cut -->
</select>
Run Code Online (Sandbox Code Playgroud)