Thursday, 10 November 2016

javascript - JQuery .click() does not work in new sortable item




I have JQuery UI Sortable+Draggable lists, and i use JQuery .click() for all sortable items, but if i drop new item from draggable list to sortable list, this item do not trigger .click() event.




$(#sortable li).click(function(){
alert('Sortable item clicked');
});


https://jsfiddle.net/1so55b0t/2/



Why?







Okay, i'm replace .click() to .on('click')



And my elements have close button with class .remove and again this does not work for new elements:



$('#sortable li').on('click','.remove',function(){
$(this).parent().remove();
});



https://jsfiddle.net/1so55b0t/4/
Why?


Answer



Try this : As you are moving the lis within DOM, it will not applied to previously bind click event handler. Better use click event delegation, which is useful for dynamic / new elements like below



$('#sortable').on('click', 'li', function(){
alert('Sortable item clicked');
});



EDIT - Use below code to add click handler for remove buttons -



$('#sortable').on('click','li .remove',function(e) {
e.stopPropagation();
$(this).parent().remove();
});


JSFiddle Demo


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...