[英]Dynamically replace drop down menu options jQuery
我有一個下拉菜單,我想在點擊事件中更改選項。 應刪除當前選擇選項並替換為新的選項數組。 這是小提琴 :
而這是另一種修復它的嘗試:
$(document).ready(function () {
var dropdown = $('<select>');
dropdown.options = function (data) {
var self = this;
if (data.length > 0) {
//how to remove the current elements
}
$.each(data, function (ix, val) {
var option = $('<option>').text(val);
data.push(option);
});
self.append(data)
}
dropdown.clear = function () {
this.options([]);
}
var array = ['one', 'two', 'three'];
dropdown.options(array);
$('body').append(dropdown);
$('#btnSubmit').on('click', function (ix, val) {
//should clear out the current options
//and replace with the new array
var newArray = ['four', 'five', 'six'];
dropdown.clear();
dropdown.options(newArray);
});
});
您需要做的就是將append()
更改為html()
因為html()
替換了元素的現有內容
dropdown.options = function (data) {
var self = this;
$.each(data, function (ix, val) {
var option = $('<option>').text(val).val(val);/* added "val()" also*/
data.push(option);
});
self.html(data)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.