I have a following code:
$.each(pk2, function(i,value) {
$('#query_form_opt_'+cell+'_2')
.append($("<option></option>")
.attr("value", i+1)
.text(value));
});
My problem is that overtime this code is called, new elements are kept on being appended. What I need to do is to clean $('#query_form_opt_'+cell+'_2')
(remove appended staff) every time this code is called.
I have tried $('#query_form_opt_'+cell+'_2').remove()
but it removes the whole div structure. $('#query_form_opt_'+cell+'_2').val('')
is doing nothing as well.
使用.empty()
只会删除子项而不是结构。
$('#query_form_opt_'+cell+'_2').empty();
remove accepts selector
which filters the element to be removed.
$.each(pk2, function(i,value) {
var el = $('#query_form_opt_'+cell+'_2');
el.remove('option');
el.append($("<option></option>").attr("value", i+1).text(value));
});
Use Empty $('#query_form_opt_'+cell+'_2').empty()
instead of remove(). empty will clear the child elements not the element itself. https://api.jquery.com/empty/
Moreover you can use the concept of flag if you don't want to append elements again and again
var flag=true;
$.each(pk2, function(i,value) {
if(flag){
$('#query_form_opt_'+cell+'_2')
.append($("<option></option>")
.attr("value", i+1)
.text(value));
}
flag=false
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.