如何使用 jQuery 在列表框中选择项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2574427/
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 do you select items in a listbox using jQuery?
提问by leora
How do you programmatically select items in a multi-select listbox using jQuery?
如何使用 jQuery 以编程方式选择多选列表框中的项目?
回答by Nick Craver
You can do it like this:
你可以这样做:
var valToSelect = "1";
$("#mySelect option[value='" + valToSelect + "']").attr("selected", "true");
Here's a quick example: http://jsfiddle.net/ZyAHr/
这是一个简单的例子:http: //jsfiddle.net/ZyAHr/
Just for kicks, here's an alternative example if it fits the situation:
只是为了踢球,如果它适合这种情况,这是一个替代示例:
var values = $("select").val();
values.push("1");
$("select").val(values);
?Here's a quick example of this: http://jsfiddle.net/FBRFY/
?这是一个简单的例子:http: //jsfiddle.net/FBRFY/
This second approach takes advantage of the fact that .val()
on a multiple<select>
element returns an array, not a string. You can get it, add or remove any values, then set it again using .val()
and it'll be updated with the new selection.
第二种方法利用了一个事实,即.val()
在多个<select>
元素上返回一个数组,而不是一个字符串。您可以获取它,添加或删除任何值,然后使用它再次设置它,它将使用.val()
新选择进行更新。
回答by Harry Sarshogh
In ListBox that have multi selection mode use it :
在具有多选模式的 ListBox 中使用它:
$('#ListBox1').find('option:selected').map(function () {
alert($(this).text());
});