如何打开/关闭$(document).click()事件或其他解决方案

How to turn $(document).click() event on/off or other solution

本文关键字:click 事件 解决方案 其他 document 何打开 关闭      更新时间:2023-09-26

我有一个div标记,当单击时,我想开始一个过程,然后单击文档上的任何地方,我想结束这个过程。到目前为止,我已经试过了:

$(document).click(end_process);
$('div_tag_id').click(start_process);

这是不好的,因为单击启动进程之后也会立即结束进程。什么好主意吗?

我相信你想要这样的东西:

$('div_tag_id').click(function(e) {
   e.stopPropagation();
   start_process(e);
});

:

http://api.jquery.com/event.stopPropagation/

在处理程序中使用stopPropagation:

$('div_tag_id').click(function(e) {
    e.stopPropagation();
    start_process();
});

当然,您只需要在start_process处理程序中阻止事件冒泡:

start_process(e) {
  e.stopPropagation();
}
编辑:看起来每个人都在同一时间说同一件事。好运!

您可以在start_process函数中调用.stopPropagation()来阻止事件冒泡到document:

function start_process(event) {
    event.stopPropagation();
    //..your code here
}
以下是.stopPropagation()的文档:http://api.jquery.com/event.stoppropagation/

使用stopPropagation来阻止点击传播到父节点。

$('div_tag_id').click(function(e){
    start_process();
    e.stopPropagation();
});

或者,将stopPropagation添加到start_process的正文中。