samedi 25 juin 2016

jquery function being called too many times even after using $(this)


With JSON data received from ajax success event I use this data to make dynamic html stuffs, something like this function loop_json(data) { var response_data = jQuery.parseJSON(data); var vip_userId = $('#userId').val(); $(response_data.vip_poll).each(function(index, value) { var t= ''; t += '<li class="vip-polls-holder" id="'+value.id+'">'; t += '<div class="user-img">'; t += '<a href="users.php?user_name='+response_data.vip_pollOwners[index].user_name+'"><img src="'+response_data.vip_pollOwners[index].user_avatar+'" class="user-img-pic img-circle" /></a>'; t += '</div>'; ... t +='</li>'; $('.vip-polls-holder-ul-mainDIV').append(t); // And so I attach some functions with these li boxes such as function1(); function2(); //and VIP_dNd_multiple(); }); } Where VIP_dNd_multiple() is-> function VIP_dNd_multiple() { // let it be called part a $trashVIP.each(function() { $(this).droppable({ accept: "#VIPgalleryMulitple"+$(this).attr('id')+" > li", activeClass: "ui-state-highlight", drop: function (event, ui) { console.log('abc'); //This prints one time } }); }); // let it be called part b $("ul.VIPgalleryMulitple > li").each(function() { var $item = $(this); $item.click(function (event) { event.preventDefault(); console.log('ok'); //This prints multiple times }); }); } The problem is VIP_dNd_multiple() is called as many times as there are li elements present on DOM and hence console gives 'ok' (part b of the function) as output multiple times which is undesirable, of course. I don't understand when I'm using click event on $(this) li why all the li elements are firing console.log action? Surprisingly, part a of the same function is outputing console correctly just once.

Aucun commentaire:

Enregistrer un commentaire