[英]Inserting dynamic option in the select tag, using Jquery
我寫了這個jQuery代碼:
$(document).ready(function(){
$(document).on('change', '.prova > .target', function() {
$('div').removeClass('prova');
$(this).parent().after($('<br>'), $('<div>', {"class": 'prova'}).append(
$('<select>', {"class": 'target'}).append(
$('<option>', {value: 'option1', text: 'Option 1'}),
$('<option>', {value: 'option2', text: 'Option 2'})
),$('<input>', {type: 'number', style: 'width: 35px', min: '1', max: '99', value: '1'}),
$('<button>', {type: 'button' , "class": 'remove_item', text: 'delete' })));
});
});
完整的例子在這里
我的代碼的目的如下:
每次從<select>
(僅最后一個)中<select>
一個新<select>
都會創建一個新的<select>
。
現在我要添加動態選項,而不是從jquery代碼添加的靜態選項。 例如,假設我有
var obj = {
"option1": "Option 1",
"option2": "Option 2"
};
如何在我的jquery代碼中集成上面列出的選項而不是靜態插入項:
...
$('<option>', {value: 'option1', text: 'Option 1'}),
$('<option>', {value: 'option2', text: 'Option 2'})
...
你可以這樣做:
var $mySelect = $('<select>', {
class: 'target'
});
$.each(obj, function (val, text) {
$mySelect.append($('<option />', {
value: val,
text: text
}));
});
var $input = $('<input>', {
type: 'number',
style: 'width: 35px',
min: '1',
max: '99',
value: '1'
});
var $button = $('<button>', {
type: 'button',
class: 'remove_item',
text: 'delete'
});
$(this).parent().after($('<br>', {
class: 'acapo'
}), $('<div>', {
class: 'prova'
}).append($mySelect, $input, $button));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.