I want to add a custum li
to an ol
with jquery event, this is my code
success: function(data) {
if (data != ''){
$ulSub = $("#firstList");
$("#Pushtype_destinationList").val(crit1);
$.each(data.dataa, function (i,item) {
$str="";
for(var key in item){ if(key != 'id'){$str+= item[key]} }
$ulSub.append( '<li class="ui-widget-content " id="'+item.id +'" >' +$str+'</li>');
});
}
}
and my code in html given as follow
<ol class="selected" id="firstList">
<li class="ui-widget-content ">text 1</li>
<li class="ui-widget-content ">text 2</li>
</ol>
and the function jquery that add an element li from the first ol to the second ol is as
jQuery('ol#firstList li').click(function() {
$(this).toggleClass('selected');
$('#result').html($('#firstList .selected').clone())
});
until now every thing work great, but when I clic on a new element add dynamically by using this function
( `for(var key in item){ if(key != 'id'){$str+= item[key]} }
$ulSub.append( '<li class="ui-widget-content " id="'+item.id +'" >' +$str+'</li>');
});)
this element cannot be added to the second <ol id="result>
as you see here, when the element text1 and text2 are added when i clic on them, but the other element which are added dynamically not
any help please
It happens because you only assign your event handler to items already existing in the DOM by the time your event handler assignment code runs.
Try:
jQuery(document).on('click', 'ol#firstList li', function() {
$(this).toggleClass('selected');
$('#result').html($('#firstList .selected').clone())
});
Look jQuery documentation for '.on' for further details.
clear html before each loop like
$ulSub.html('');
PUT fellow code
success: function(data) {
if (data != ''){
$ulSub = $("#firstList");
$("#Pushtype_destinationList").val(crit1);
$ulSub.html('');
$.each(data.dataa, function (i,item) {
$str="";
for(var key in item){ if(key != 'id'){$str+= item[key]} }
$ulSub.append( '<li class="ui-widget-content " id="'+item.id +'" >' +$str+'</li>');
});
}
}
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.