jQuery .click被多次调用 [英] jquery .click being called multiple times

查看:82
本文介绍了jQuery .click被多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery尝试设置div的"click"方法时,我得到了意外的结果.请参阅此jsfiddle .确保打开控制台窗口.单击该单词几次,然后查看控制台输出.当仅应单击一次时,click函数会被调用多次.

I am getting unexpected results with jQuery trying to set the "click" method of a div. Please see this jsfiddle. Be sure to open the console window. Click the word a few times and watch the console output. The click function gets called multiple times when it should only be called once.

最后注释掉的代码可以正常工作.难道我做错了什么?我是jQuery新手.

The commented out code at the end works just fine. Am I doing something wrong? I'm new to jQuery.

代码如下:

function toggleDiv(status)
{
    console.log("toggleDiv(" + status + ")");
    if (status) {
        $("#test").html("Goodbye");
    }
    else  {
        $("#test").html("Hello");
    }
    $("#test").click(function() {
        toggleDiv(!status);
    });

    // Non-jquery method works fine....
    //document.getElementById("test").onclick = function () {
    //    toggleDiv(!status);
    //}
}​

更新:看起来有很多方法可以给这只猫蒙皮.真正的问题是我不了解jQuery的单击"功能会添加ADDS另一个处理程序.我认为它可以代替当前的处理程序.

Update: looks like there are lots of ways to skin this cat. The real issue here was my not understanding that the jQuery "click" functions ADDS another handler. I thought it REPLACED the current handler.

推荐答案

每次单击它都将设置一个新的.click() eventHandler(这反过来会创建更多事件).附带说明一下,尝试永远不要在DOM元素上使用onclick / onmouseover / onmouseout / etc事件.在Internet Explorer中,这些创建脚本块(您可以清楚地看到您是否使用Visual Studio.具有成千上万个此类页面的页面会极大地降低性能!

You are setting a new .click() eventHandler each time you keep clicking it (which in turn creates even more events). On a side note, try to never use onclick / onmouseover / onmouseout / etc events on DOM elements. In Internet explorer these create script blocks (that you can visibly see if you use Visual Studio. Pages with thousands of these slow down performance tremendously!

您似乎正在尝试实现以下目标:

It looks like you are trying to achieve this:

jsFiddle演示版

$("#test").on('click', function() {
    var this$   = $(this),
        _status = !!this$.data('status'); // force to boolean
                  // ^will default to false since we have no data-status attribute yet

    this$.html(_status ? 'Hello' : 'Goodbye')
         .data('status', !_status);
});​

这篇关于jQuery .click被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆