【问题标题】:jquery function being called too many times even after using $(this)即使在使用 $(this) 之后,jquery 函数也被调用了太多次
【发布时间】:2016-10-11 01:54:22
【问题描述】:

通过从 ajax 成功事件接收到的 JSON 数据,我使用这些数据来制作动态 html 内容,类似于这样

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();
   });
}

VIP_dNd_multiple() 在哪里->

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
        });
    });
}

问题是 VIP_dNd_multiple() 被调用的次数与 DOM 上存在的 li 元素一样多,因此控制台多次给出“ok”(函数的 b 部分)作为输出,这当然是不可取的。我不明白当我在 $(this) li 上使用 click 事件时,为什么所有 li 元素都在触发 console.log 操作?
令人惊讶的是,同一函数的 a 部分只正确输出了一次控制台。

【问题讨论】:

    标签: jquery ajax


    【解决方案1】:

    我不知道它是否对此有帮助,但是这段代码为我节省了很多次以防止发生多个事件:

    $item.click(function (event) {
        event.preventDefault();
        if (event.handled !== true) {
            event.handled = true;
            //Your stuff
            console.log("ok");
        }
    })
    

    【讨论】:

    • 老实说,我真的不知道,几年前我遇到过这个问题,我在 SO 上找到了这段代码,从现在开始,一直使用它。当您在同一元素上多次添加Listener 时,它可以防止多个事件。
    【解决方案2】:

    $TrashVIP 的值是多少?好像没有传入 LI 项,而是读取了只有一项的 UL 项,所以才会打印一次。

    第二个函数调用每个 LI 项,因此如果您有 10 个 LI 项,并且单击其中一个 LI,它确实会通过循环并多次呈现 OK。

    在我看来,您并不真的需要第二个each 函数,而是将click 函数原样放置,一旦单击任何LI 项,它就会被触发。

    $("ul.VIPgalleryMulitple > li").click(function() {
        event.preventDefault();
        console.log("ok"); 
    });
    

    Sample Fiddle

    【讨论】:

    • 你说得对,我不需要每个循环。但实际上我使用 each 来获取 $(this) 以便该函数仅在我单击的 li 上调用一次,而不是全部。
    • 点击函数和添加的每个函数给出了相同的结果,jsfiddle.net/1cyzq39h/1
    • 如果去掉each函数,使用$("ul.VIPgalleryMulitple &gt; li")触发onclick事件,click事件已经绑定到每个LI级别,所以控制台每次点击只会显示一次它获取特定的 LI,而不是整个 UL > LI 列表。
    • 当LI元素在html中静态加载时,你所说的效果很好。但是我在 ajax 成功中动态加载它们(请参阅函数 loop_json() ),然后将 VIP_dNd_multiple() 附加到每个循环。在那种情况下,无论我做了什么输出都会打印多次。
    【解决方案3】:

    我删除了 $.each 函数,因为它可能是问题的根源。相反,我切换到“开”方法。此外,我在第一次单击后删除了锚元素的 id,以在第一次单击后丢弃进一步的事件。我结合 A. Rossi 答案的最终解决方案 ->

    $("ul.VIPgalleryMulitple > li").on('click', function (event) {
    
            if (event.handled !== true) {
                event.handled = true;
    
                var $item = $( this ),
    
                var ids = $(this).attr('id');
    
                console.log('ok'); 
    
                $(this).find('a').removeAttr('id');
            }
            return false;
        });
    

    【讨论】:

      猜你喜欢
      • 2011-10-16
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 2014-11-02
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多