如何防止在单击子链接时触发父元素的onclick事件?

510
我正在使用jQuery使一个div可点击,在这个div中还有锚点。我遇到的问题是,当我点击一个锚点时,两个点击事件都会触发(对于div和锚点)。如何防止在单击锚点时触发div的onclick事件?
以下是错误的代码:
JavaScript
var url = $("#clickable a").attr("href");

$("#clickable").click(function() {
    window.location = url;
    return true;
})

HTML

<div id="clickable">
    <!-- Other content. -->
    <a href="http://foo.example">I don't want #clickable to handle this click event.</a>
</div>
26个回答

4

e.stopPropagation()是一个正确的解决方案,但如果您不想给内部锚点附加任何事件处理程序,您可以将此处理程序简单地附加到外部div:

e => { e.target === e.currentTarget && window.location = URL; }

3

以下是使用Angular 2+的示例:

例如,如果您想要在用户点击模态组件外部时关闭它:

// Close the modal if the document is clicked.

@HostListener('document:click', ['$event'])
public onDocumentClick(event: MouseEvent): void {
  this.closeModal();
}

// Don't close the modal if the modal itself is clicked.

@HostListener('click', ['$event'])
public onClick(event: MouseEvent): void {
  event.stopPropagation();
}

3

var inner = document.querySelector("#inner");
var outer = document.querySelector("#outer");
inner.addEventListener('click',innerFunction);
outer.addEventListener('click',outerFunction);

function innerFunction(event){
  event.stopPropagation();
  console.log("Inner Functiuon");
}

function outerFunction(event){
  console.log("Outer Functiuon");
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Pramod Kharade-Event with Outer and Inner Progration</title>
</head>
<body>
<div id="outer" style="width:100px;height:100px;background-color:green;">
  <div id="inner" style="width:35px;height:35px;background-color:yellow;"></div>
</div>
</body>
</html>


3

如果它在行内文本中,在HTML中请尝试这样使用:

onclick="functionCall();event.stopPropagation();

1

你需要阻止事件冒泡到父级元素(div)。 关于事件冒泡的部分可以参考这里,jQuery特定API信息请看这里


很棒。谢谢你关于事件冒泡的信息。 - Jonathon Watney

0

这里是一个非 jQuery 的解决方案,对我很有效。

<div style="background:cyan; width:100px; height:100px;" onclick="if (event.srcElement==this) {console.log('outer');}">
    <a style="background:red" onclick="console.log('inner');">Click me</a>
</div>


0

对于那些不使用jQuery的人

document.querySelector('.clickable').addEventListener('click', (e) =>{
    if(!e.target.classList.contains('clickable')) return
    // place code here
})

你好,谢谢!这似乎在很大程度上重复了现有答案(https://dev59.com/aXM_5IYBdhLWcg3wdy5g#29499060)。请编辑以解释这与现有答案的不同之处/更好之处! - Edward

0

要将某些子元素指定为不可点击,请按以下示例编写CSS层次结构。

在此示例中,我停止传播到表格中带有类“.subtable”的tr内的td内的任何元素(*)。

$(document).ready(function()
{    
   $(".subtable tr td *").click(function (event)
   {
       event.stopPropagation();
   });

});

0

您可以检查目标是否不是您的 div 元素,然后在父元素上触发另一个点击事件,之后您将从处理程序中“返回”。

$('clickable').click(function (event) {
    let div = $(event.target);
    if (! div.is('div')) {
       div.parent().click();
       return;
    }
    // Then Implement your logic here
}

0
这是一个基于React的解决方案示例。在我的情况下,我有一个具有透明外包装的模态联系表单。我希望在模态框外部的任何点击都能关闭模态框。
import React, { useState } from 'react';

function Component() {
  const [contactOpen, setContactOpen] = useState(false);
  const handleContactToggle = () => {
    if (e.target === e.currentTarget) {
      //e.target ===  item the onClick is attached to. 
      //e.currentTarget ===  item that received the click
      // If these do not match the click is somewhere inside the InnerComponent
      setContactOpen(!contactOpen);
    }
  };
  const ContactModalClass = (contactOpen) ? styles.contactModalOpen : styles.contactModalClosed

  function handleModalToggle(e) {
    if (e.target === e.currentTarget) {
      handleContactToggle();
    }
  }
  <div className={ContactModalClass} onClick={e => handleContactToggle(e)} id='OuterWrapper-Click-To-Close'>
    <InnerComponent id='Inner-Form-Click-Does-Not-Trigger-Outer-Function' />
  </div>
}

注意:这是我在React搜索中遇到的问题,因此给出了React的答案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接