[英]on selected value populating the dropdown list
我有目錄列表,這些目錄是帶有模板的主題。 當選擇任何主題時,我將主題下拉列表與主題列表一起列出,它將使用其(所選主題的)模板填充另一個下拉列表。
這是我的javascript代碼,選擇主題后我可以獲取模板列表,但是當我嘗試更改它時,它正在復制模板下拉列表中的值。
$('#theme').on('change', function() { var selectedTheme = $(this).find('option:selected').val(); $.ajax({ url: '/admin/content/templates?theme=' + selectedTheme, type: 'GET', dataType: 'json', contentType: "application/json", data: JSON.stringify(selectedTheme), success: function(data) { console.log(data) $.each(data, function(idx, value) { $('#template').append('<option>' + value + '</option>'); }); }, error: function(data) { console.log("There are some errors") } }); });
這是我獲取主題模板的控制器方法。
// getting the list of available templates
@RequestMapping(value="/templates", produces="application/json")
@ResponseBody
List<String> getTemplates(@RequestParam("theme") String theme) {
String path = "src/main/webapp/WEB-INF/views/themes/" + theme
List<String> templates = []
new File(path).eachFileMatch(~/.*.twig/) { file->
file.path
templates.add(file.getPath())
}
templates
}
誰能告訴我為什么它要復制模板下拉列表中的值?
嘗試添加一行以清除模板下拉列表,然后重新填充它:
success: function(data) {
console.log(data)
$('#template').empty(); //<======
$.each(data, function(idx, value) {
$('#template').append('<option>' + value + '</option>');
});
},
您可以將數據存儲在字符串中並使用html
轉儲:
var str = "";
$.each(data, function(idx, value) {
str += '<option>' + value + '</option>';
});
$('#template').html(str);
與在每個循環上編寫代碼相比,我認為這樣做的性能更高。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.