在单击的元素外部设置 html 单击处理程序会立即触发

问题描述 投票:0回答:1

我有一个日历图标,其中有一个

onclick
处理程序,用于显示弹出日历,我想对其进行设置,以便单击日历弹出窗口之外的任何位置都会将其关闭。

但是,它会立即关闭弹出窗口。

示例代码演示了问题:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>

<body>
<img src='https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png' width='100px' onclick='fire()' />

<script>
function fire() {
  console.log('fire');

  $('body').on('click', (e) => {
    console.log('clicked outside');
    
    $('body').off('click');
  });
}
</script>
</body>
</html>

因此运行上面的代码片段,输出“fire”,然后立即“clicked Outside”...但是为什么,我只在

fire
函数中附加处理程序,那么它如何立即触发?

javascript html jquery events
1个回答
0
投票

您代码中的问题是,当您单击图标时,会触发日历图标单击事件和正文单击事件。

参见:https://api.jquery.com/event.stopPropagation/

在一个元素上触发的事件会传播到其父元素。 在您的情况下,图标单击事件立即传播到 body 元素。

您可以停止日历图标事件的传播:

function fire(event) {
  console.log("fire");
  // Stop the event from spreading
  event.stopPropagation();

  // Listen to clicks on the body
  $("body").on("click", function () {
    console.log("clicked outside");
    // Remove the listener after it has been triggered
    $("body").off("click");
  });
}

然后,修改 HTML 以将事件对象传递给您的 fire() 函数:

<img src='https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png' width='100px' onclick='fire(event)' />

日历图标上的点击事件不会传播到body上,只有在日历图标之外点击才会触发body上的点击事件!

© www.soinside.com 2019 - 2024. All rights reserved.