ada*_*101 5 javascript jquery select
如果我有这个选择框:
<select id="s" name="s">
<option value="0">-</option>
<option value="1">A</option>
<option value="2" selected>B</option>
<option value="3">C</option>
</select>
Run Code Online (Sandbox Code Playgroud)
如果我尝试运行$("#s").val("4"),则选择变为"0".(请参阅此处的行为:http://jsfiddle.net/4NwN5/)如何将其设置为如果我尝试将选择框设置为选择框中不存在的值,则没有任何更改?
你可以这样试试:
var toSel = 3; // Say your value is this
if($("#s option[value=" + toSel +"]").length > 0) //Check if an option exist with that value
{
$("#s").val(toSel); //Select the value
}
Run Code Online (Sandbox Code Playgroud)
或者只是使用prop()
$("#s option[value='" + toSel +"']").prop('selected', true);
Run Code Online (Sandbox Code Playgroud)
小智 1
// grab the selected
var s = $("#s");
// cache the current selectedIndex
var idx = s[0].selectedIndex;
// set the value
s.val("4");
// If it was set to `0`, set it back to the original index
s[0].selectedIndex = s[0].selectedIndex || idx;
Run Code Online (Sandbox Code Playgroud)
你可以将其整合到一个插件中:
jQuery.fn.selectVal = function (val) {
return this.each(function () {
if (this.nodeName === "SELECT") {
var idx = this.selectedIndex;
$(this).val(val);
var newOpt = this.options[this.selectedIndex];
if (newOpt.value !== ("" + val))
this.selectedIndex = idx;
}
})
};
$("#s").selectVal(4);
Run Code Online (Sandbox Code Playgroud)