簡體   English   中英

無法使用jQuery選擇SELECT中的多個OPTIONS

[英]Unable to select multiple OPTIONS in a SELECT with jquery

我有一個HTML選擇元素,它允許多個選擇。 我用ajax請求的結果填充選項。 我將自定義屬性添加到選項。 在一個實例中,當另一個ajax請求完成時,我想更新多選值。 我有以下javascript方法可以進行此選擇:

// select = id of the select control.
// selected = list of json objects with an id representing those that are selected.
updateSelection = function( select, selected ) {
    $('#'+select+' option').each( function() {
        var item = $(this);
        $.each(selected, function() {
            item.removeAttr( "selected" );
            if ( this.id === parseInt(item.attr("optionId"), 10 )) {
                alert( "selecting " + item.text());
                item.attr("selected", true );
            }
        });
    });
};

運行該方法之前的HTML如下所示:

<select id="putPlatforms" multiple="multiple">
    <option optionid="1" optionversion="1">PC</option>
    <option optionid="3" optionversion="1">Xbox 360</option>
</select>

在僅選擇“ PC”的情況下,將進行選擇並將其反映在UI中。 如果僅選擇“ Xbox 360”,則相同。 如果應同時選擇兩個選項,我會看到警告,指出將同時選擇這兩個選項,但僅選擇了Xbox 360。

使用這個問題的答案,我能夠使它起作用。 我將功能更改為以下內容:

// select = id of the select control.
// selected = list of json objects with an id representing those that are selected.
updateSelection = function( select, selected ) {
    $('#'+select+' option').attr('selected', false );
    $.each(selected, function() {
        $('#'+select+' option[optionid='+this.id+']').attr('selected', true );
    });
};

暫無
暫無

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

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