1

我有这个多选列表:

<select id="vendors" name="vendors" multiple="multiple">
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
    <option value="5">E</option>
</select>

当页面加载时,我正在加载需要在我的选择列表中选择的 id 列表。这是我正在尝试的方法:

var vendors = GetVendorArray();  // list of vendor ids I want selected

$.each(vendors, function(index, item) {
    $("#vendors").filter(function() {
        return $(this).val() == item; 
    }).attr('selected', true);
});

但这不起作用,没有选择任何项目。有人知道我在做什么错吗?

4

2 回答 2

4

最简单的方法是将整个数组作为值传递给selectusing val()。带mulitple select值的是一个数组

$('#vendors').val(  GetVendorArray())

演示:http: //jsfiddle.net/sPKAY/

您采用的方法的问题是没有循环option标签

于 2013-03-04T02:13:42.053 回答
1

filter减少匹配元素的集合以匹配附加的选择器/回调 fn。输出。您需要定位<option>元素,而不是下拉列表本身,因为您尝试根据其值是否与数组内容匹配来选择选项。

var vendors = GetVendorArray();  // list of vendor ids I want selected

$.each(vendors, function(index, item) {

    //you're filtering options, not the list itself
    $("#vendors > option").filter( function() {
        return $(this).val() == item; 
    }).prop('selected', true); //use .prop, not .attr
});
于 2013-03-04T02:08:03.927 回答