如何使用 jQuery 选择下拉选项? [英] How to use jQuery to select a dropdown option?
本文介绍了如何使用 jQuery 选择下拉选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有可能让 jQuery 在下拉框中选择一个 ,比如说第 4 项?
我希望用户单击一个链接,然后让 框更改其值,就像用户通过单击
解决方案
怎么样
$('select>option:eq(3)').attr('selected', true);
示例:
$('select>option:eq(3)').attr('selected', true);
预><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><选择><选项>1</选项><option>2</option><选项>3</选项><选项>4</选项><选项>5</选项></select>
对于现代版本的 jquery,您应该使用 .prop()
而不是 .attr()
$('select>option:eq(3)').prop('selected', true);
示例:
$('select>option:eq(3)').prop('selected', true);
预><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><选择><选项>1</选项><option>2</option><选项>3</选项><选项>4</选项><选项>5</选项></select>
I was wondering if it’s possible to get jQuery to select an <option>
, say the 4th item, in a dropdown box?
<select>
<option></option>
<option></option>
<option></option>
<option></option>
<option></option>
</select>
I want the user to click a link, then have the <select>
box change its value, as if the user has selected it by clicking on the <option>
.
解决方案
How about
$('select>option:eq(3)').attr('selected', true);
Example:
$('select>option:eq(3)').attr('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
for modern versions of jquery you should use the .prop()
instead of .attr()
$('select>option:eq(3)').prop('selected', true);
Example:
$('select>option:eq(3)').prop('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
这篇关于如何使用 jQuery 选择下拉选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文