我有一个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 ,我需要在上面描述的'select'中添加一个选项,但我尝试的方法不起作用。我需要帮助正确使用$.each
,我如何在这种情况下使用它。有人可以帮忙吗?上面的例子只添加了第一个,缺少所有其他的。
答案 0 :(得分:0)
应该是这样的:
$.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)。