在点击事件中分配点击事件处理程序 [英] Assigning a click-event-handler inside a click-event

查看:33
本文介绍了在点击事件中分配点击事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 jQuery 中处理点击事件时遇到了一些奇怪的行为.

看看这个小提琴

$('#button').click(function() {$(document).one('click', function() {警报('点击');});});

此代码将点击事件处理程序绑定到某个按钮.单击此链接时,应将事件处理程序添加到文档中,并在下次单击文档时提醒已单击".

但是当点击这个按钮时,点击"会立即得到提醒,无需再次点击.显然,将新处理程序绑定到文档的点击事件被冒泡到文档中并立即运行刚刚分配的处理程序.

这种行为似乎非常违反直觉.我的目的是在点击按钮时显示一个元素,并在点击该元素外时再次隐藏它.

$('#button').click(function() {//显示一些元素$(document).one('click', function() {//再次隐藏元素});});

但这会导致元素立即被隐藏.

有没有人有解决这个问题的方法?

解决方案

可以阻止事件向上传播 DOM.

$('#button').click(function(e) {e.stopPropagation();$(document).one('click', function(e) {警报('点击');});});

JS Fiddle: http://jsfiddle.net/7ymJX/6/

I have encountered some strange behavior when dealing with click-events in jQuery.

Have a look at this Fiddle

$('#button').click(function() {
    $(document).one('click', function() {
        alert('clicked');
    });
});

This code is binding a click-event-handler to some button. On clicking this link, an event-handler should be added to the document, alerting "clicked" when the document is next clicked.

But when clicking this button, "clicked" gets immediately alerted without another click. So apparently the click-event which binds the new handler to the document gets bubbled to the document and immediately runs the just assigned hndler.

This behavior seems very counter-intuitive. My intention was showing an element when clicking on the button and hiding it again on clicking outside this element.

$('#button').click(function() {
    // Show some element

    $(document).one('click', function() {
        // Hide the element again
    });
});

But this results in the element being hidden immediately.

Does anyone have a solution to this problem?

解决方案

The event can be prevented from propagating up the DOM.

$('#button').click(function(e) {
    e.stopPropagation();
    $(document).one('click', function(e) {
        alert('clicked');
    });
});

JS Fiddle: http://jsfiddle.net/7ymJX/6/

这篇关于在点击事件中分配点击事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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