我需要根据它的索引而不是它的值来更改选项。
我的当前代码:HTML
<select name="locations" id="locations">
<option value="1">loc1</option>
<option value="2">loc2</option>
</select>
<a id="location-1" href="#">Loc 1</a>
<a id="location-2" href="#">Loc 2</a>
Javascript
$(document).ready( function() {
$('#location-1').click(function() {
alert('first clicked')
$("#locations").val($("#locations option:first").val());
});
$('#location-2').click(function() {
alert('second clicked')
$("#locations").val($("#locations option:second").val());
});
});
如何通过jquery更改#locations的VAL。
https://jsfiddle.net/go71tovr/2/
$('#location-1').click(function() {
alert('first clicked')
$('#location :nth-child(1)').prop('selected', true); // To select via index
});
$('#location-2').click(function() {
alert('second clicked')
$('#location :nth-child(2)').prop('selected', true); // To select via index
});
});
我更新了代码,上面的现在可以工作了!
$('#location :nth-child(2)').prop('selected', true); // To select via index
事实证明,这是正确的拼写方式。