使用.prop('selectedIndex',#)的JQuery集选择不起作用

JQuery set select using .prop('selectedIndex', #) not working

本文关键字:JQuery 不起作用 选择 prop selectedIndex 使用      更新时间:2023-09-26

我使用以下行从选择菜单中设置一个选项:

$('select').prop('selectedIndex', 2)

以以下网站为例:http://shoebaloo.nl/michael-by-michael-kors-chelsea-skate-leo-bruin-dessin-285000097-women-sneakers.html

我确实看到选择选项转到了第二个选项,但它不会像实际点击第二个按钮那样有效果。

有人能帮我吗?这样页面就能识别我"点击"了一个选项吗?

您需要使用选择器来选择该选项。

$('select option:eq(2)').prop('selected', true)

如果您希望手动触发单击或更改事件,可以使用.trigger('click').trigger('change')方法。

http://jsfiddle.net/j5v6tp7t/4/

您所要做的就是使用.val()来设置值。

例如:

$('select').val('2')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
    <option value="1">a</option>
    <option value="2">b</option>
    <option value="3">c</option>
    <option value="4">d</option>
</select>

您的表达式是正确的,但正确的语法是:

$('select').get(0).selectedIndex = 2;

http://jsfiddle.net/f4s762cq/