Abhishek Sinha Abhishek Sinha - 4 months ago 26
Ajax Question

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>';
// And so I attach some functions with these li boxes such as
function2(); //and

Where VIP_dNd_multiple() is->

function VIP_dNd_multiple() {

// let it be called part a
$trashVIP.each(function() {
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) {
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.


I don't know if it can help for this, but this code save me many times for prevent multiple event :

$item.click(function (event) {
    if (event.handled !== true) {
        event.handled = true;
        //Your stuff