当选项的值是字符串时,是否可以更改选择的值?似乎不起作用。
<select class="value1">
<option value="=">Equal To</option>
</select>
$('.value1').val('=').change();
您可以使用的另一个选项是设置选择的selectedIndex
属性。
var $select = $('.value1');
var $targetOption = $select.find('option').filter(function(){
return this.value === '>';
});
$select.prop('selectedIndex', $targetOption.index());
console.log($select.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="value1">
<option value=""></option>
<option value="=">Equal To</option>
<option value=">">Greater Than</option>
<option value="<">Less Than</option>
</select>
您不需要调用.change()
方法(该方法有效地调用change
事件(,除非您的用例比您在此处显示和询问的内容更多。
只需更新.val()
即可修改元素的value
。现在,需要明确的是,您的<select>
(正如您所编写的那样(已经具有=
的值,因为列表中只有一个<option>
,并且该option
已经=
为其值静态设置。
// Because you only have one <option> in the list, that <option>
// becomes the default and it already has a value of "=", so we
// really don't need to do anything to get the <select> to take
// on the value of its only <option>
console.log("Default value of the select is: " + $('.value1').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="value1">
<option value="=">Equal To</option>
</select>
但是,请理解value
与下拉列表中显示的选项不同。<select>
元素的value
是元素当前存储在内存中的值。内存中的内容与下拉列表中显示的内容不同。
为此,您必须修改相应option
元素的.text()
。
// To change what is shown in the drop down, you have
// to modify the corresponding <option> element's text
$('.value1 > option').text('=');
console.log("The <select> element's value is: " + $('.value1').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="value1">
<option value="=">Equal To</option>
</select>
最后,将它们与更现实的列表放在一起:
// Start with the default value of the <select>,
// which, by default, is the value of the first <option>
console.log("Initial (default) value of the <select> is: " + $('.value1').val());
// Change the <select> value to something else, but it must be one
// of the values defined for one of the <option> elements. This will
// cause that option to become selected and shown in the list
$('.value1').val('>');
console.log("Current value of the <select> is now: " + $('.value1').val());
// Modify the text that corresponds to one of the <option> elements
$('.value1 > option:nth-child(2)').text('< Than');
// But changing the text doesn't change the underlying value of that <option>
console.log("<option>'s value is: " + $('.value1 > option:nth-child(2)').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="value1">
<option value="=">Equal To</option>
<option value="<">Less Than</option>
<option value=">">Greater Than</option>
<option value="<=">Less Than or Equal To</option>
<option value=">=">Greater Than or Equal To</option>
</select>