簡體   English   中英

如何使用javascript / jquery添加動態選項?

[英]How to add dynamic options using javascript/jquery?

我有一個gsp頁面,在該頁面上有一個' <g:select> '元素為:

<label class="control-label">Applicable Offices:</label>
<span class="span6">
    <select name="data.OfficeId" class="required j-office-select" style="height:26px;padding:1px;">
        <option value="0">Select an office...</option>
    </select>
</span>

我必須使用JavaScript為此選擇動態添加更多的“選項” 我的JavaScript部分如下所示:

$.ajax({
    url: epcm.urlManager.getUrl({controller: 'controllerName', action:'methodName'}),
    cache: false,
    contentType: "application/json",
    type: "POST",
    dataType: "json",
    data: JSON.stringify(params),
    success: function(officeData) {
        var selectOffice = dialog.find('.j-office-select');
        selectOffice.empty();
        // OfficeData is a list . For each officeData , I need to add an option to the’ select’, but ways I tried did not work.I need to know the proper use of $.each and how can I use that in this context
        selectOffice.append('<option value="'+officeData.id+'">'+officeData.regionName+'</option>' );
        selectOffice.removeAttr('disabled');
        window.location.reload();
    }
});

“成功”中的“ OfficeData”是一個列表。 對於每個officeData ,我都需要在上述“選擇”中添加一個選項,但是我嘗試的方法不起作用。 我需要正確使用$.each以及在這種情況下如何使用它的幫助。 有人可以幫忙嗎? 上面的示例僅添加了第一個,而忽略了所有其他。

應該是這樣的:

$.each(officeData, function(index, item){
   selectOffice.append('<option value="'+item.id+'">'+item.regionName+'</option>' );
} );

但是,在您的示例中,officeData似乎不是一個集合,因為officeData.id和officeData.regionName沒有嵌套在項目內部。 您可以使用console.log(officeData); 將數據結構輸出到瀏覽器控制台(假設您使用的是Chrome或FireFox + devtools之類的東西)。

暫無
暫無

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

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