簡體   English   中英

使用.prop('selectedIndex',#)的jQuery設置選擇不起作用

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

我正在使用以下行從選擇菜單中設置選項:

$('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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM