Javascript 如何使用JQuery选择第n个选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4222950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use JQuery to select the nth option
提问by Cheok Yan Cheng
I have the following HTML
我有以下 HTML
<select onchange="this.form.submit()" name="name">
<option value="9995101E01#17201044055PM">9995101E01#17201044055PM</option>
<option value="GRR-Example">GRR-Example</option>
<option value="admin">admin</option>
<option value="123w">123w</option>
</select>
May I know how I can use JQuery to option with value "admin"?
我可以知道如何使用 JQuery 来选择带有“admin”值的选项吗?
回答by Alex
Like this:
像这样:
$("select[name='name'] option:eq(2)").attr("selected", "selected");
EDIT:
编辑:
To do what you want in your new edit, that is, select the option that has the value of admin
:
要在新编辑中执行您想要的操作,即选择值为 的选项admin
:
$("select[name='name'] option:contains('admin')").attr("selected", "selected");
回答by Ruben Arevalo
I think the nth-child
pseudo-class is what you're looking for:
我认为nth-child
伪类就是你要找的:
$('select option:nth-child(3)').attr('selected', 'selected');
回答by Denis Matafonov
I'd not advice setting value of select by using .attr('selected', 'selected')
.
It's bad practice. If two options have 'selected' attribute - then what is the value of select?
我不建议使用.attr('selected', 'selected')
. 这是不好的做法。如果两个选项都有 'selected' 属性 - 那么 select 的值是多少?
Here is the simple and easy version that will work:
这是一个简单易行的版本:
$('select[name="name"]').val('admin');
回答by Souvik Ghosh
Just updating in case it helps someone. I had a similar requirement but in my case the dropdown was stored as a JavaScript variable. Also I liked how Denis Matafonovsuggested to make the option in question selected. So here's the final block of code:
只是更新以防万一它对某人有帮助。我有类似的要求,但在我的情况下,下拉列表存储为 JavaScript 变量。我也喜欢Denis Matafonov建议选择相关选项的方式。所以这是最后的代码块:
var target_dd = $('select[name=name]');
$(target_dd).val($(target_dd).find('option:eq(2)').html());
回答by Tomasz Mularczyk
If you want to select nth option andtrigger onchange event then:
如果要选择第 n 个选项并触发 onchange 事件,则:
function selectOption(nr) {
var select = $("select");
if (select.children().length >= nr) {
let value = select.find('option:eq(' + nr + ')').val();
select.val(value).change();
}
}