点击事件的jQuery多次发生

时间:2016-01-31 07:20:45

标签: javascript jquery

我试图让某些元素在点击屏幕上的任何地方时显示或消失。这是我为它写的代码:

<script>
    var tonks = 1;
    $(document).ready(function(){
        $(".navbar").css("zIndex", 2);
        $("*").unbind('click').click(function (e) { 
            if(tonks == 1) {
                $(".navbar").slideUp();
                $(".overlay").fadeOut();
                tonks = 0;
            }
            else {
                $(".navbar").slideDown();
                $(".overlay").fadeIn();
                tonks = 1;
            }    
        });
     });
</script>

但由于某种原因,每次点击会使元素出现和消失3次 我在这里读到了关于这个问题的类似问题,但是所有这些问题似乎都是关于点击的复杂事件,而我的是非常简单的代码。 我在调用click之前尝试使用unbind,但是没有用。   有什么建议吗?

3 个答案:

答案 0 :(得分:3)

在处理事件后使用event.stopPropagation(),它将阻止父dom元素处理程序处理事件。

答案 1 :(得分:0)

您面临事件冒泡的问题。当您使用$("*")时,它会将事件绑定到每个元素,当您单击任何子元素时,它还会为父项触发事件。使用$(document).click代替$("*").unbind('click').click,如下所示。

$(document).click(function (e) { 
   // do your stuff here
})

答案 2 :(得分:0)

使用 * 时,您需要创建一个列出网页中每个元素的集合。因此,您可以单独对所有元素执行bind()。这就是您重复拨打处理程序的原因。

您的事件会冒泡到目标元素的父级,然后是下一个父级,依此类推,直到它到达DOM的顶部。

$("*") // Don't use this

相反,如果你专注于一个节点,你只会触发一个事件。

$(document) // Use this instead

此外,jQuery事件是命名空间 - 所以&#39;点击&#39;不像click.namespace&#39;那样可取。让我告诉你。

HTML:我正在制作两套用于

的套装
<div id="1" class="one"></div>
<div id="2" class="one"></div>
<div id="3" class="one"></div>
<div id="4" class="two"></div>
<div id="5" class="two"></div>
<div id="6" class="two"></div>

CSS:有些人撒了,所以我们可以有一些非常基本的风格 - 为了看到发生的事情

div {width:100px;height:100px;margin:10px;background:red;float:left;}

.blue { background: blue;}
.green {background: green;}

jQuery:我已经通过bind附加了一些函数,然后使用unbind再次将它们分离。

// Here we make two groups to play with
var one = $('.one');
var two = $('.two');

// Use named functions for better readability - try to avoid anonymous function
// directly attached from within your "bind". Better still use external functions
// to be more DRY - as show here 

// This will toggle blue on group one
function addblue () {
  $(one).toggleClass('blue');
}

// This will toggle green on group two
function addgreen () {
  $(two).toggleClass('green');
}

// Now we can call them against our bind function
// Noticed that I've namespaced them - which is better than
// listening to all of a given event
$(document).bind('click.blue', addblue);
$(document).bind('click.green', addgreen);

现在,我们可以解除对某些名称空间的绑定 - 并且不必立即将其全部关闭。

// This would unbind all click handlers
// We would only do this when we're sure we want to unbind all of them
$(document).unbind('click');

// This would unbind all click handlers on green
$(document).unbind('click.green');

// This would unbind all click handlers on blue
$(document).unbind('click.blue');

// We can go one better and unbind a namespace and capture all events within it
// Which means we'd unbind 'click', 'mouseover', 'custom' and so on.
$(document).unbind('.green');

这是一个让你前进的工作方式:https://jsfiddle.net/likestothink/me2992p5/

相关问题