javascript 当孩子被点击时触发父点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19997374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:29:03  来源:igfitidea点击:

trigger parent click event when child is clicked

javascriptjqueryhtmlevents

提问by Alireza Farahani

I'n new to javaScript and jQuery. How is this possible to call the click event of parent element when you click its child? I have this structure in my code:

我不熟悉 javaScript 和 jQuery。当您单击其子元素时,如何调用父元素的单击事件?我的代码中有这个结构:

<ul id="pc5">
   <li><a href="#">book</a>
   </li>
</ul>

I want something like this:

我想要这样的东西:

$("a").click(ul.click);

Any help would be appreciated.

任何帮助,将不胜感激。

EDIT: in my ul click function I need ul id attribute. something like this:

编辑:在我的 ul 点击功能中,我需要 ul id 属性。像这样:

 ul.click(function(e){alert(e.target.id);

so when link is clicked, event.target isn't ul element.

所以当链接被点击时, event.target 不是 ul 元素。

采纳答案by Alex

You dont need to trigger element click events when child elements are clicked, the click event bubblesup the dom tree if you dont stop propagation.

单击子元素时不需要触发元素单击事件,bubbles如果不停止传播,则单击事件会在 dom 树上触发。

Here you can see it working: jsfiddlejust click on the blue span, the click event will bubble up to the ul :)

在这里你可以看到它的工作:jsfiddle只需点击蓝色跨度,点击事件就会冒泡到 ul :)

Updated question

更新的问题

If you want the id of the ul, simply to:

如果您想要 ul 的 id,只需:

$('ul li a').click(function() {
  var id = $(this).closest('ul').attr('id');
});

Which would be even easier like so:

像这样会更容易:

$('ul').click(function() {
   var id = $(this).attr('id');
   alert(id);
});

Working fiddle

工作小提琴

This should work if you click on an since it bubbles up

如果您单击它,这应该会起作用,因为它会冒泡

回答by Kasyx

You should read about event propagationin jQuery. In few words: when user clicks on athen event will be propagated up in DOM tree.

您应该阅读jQuery 中的事件传播。简而言之:当用户点击时,a事件将在 DOM 树中向上传播。

回答by Andrei

I had html like this:

我有这样的html:

<a href="?chk=1">
    <input id="CHK_1" name="CHK[1]" type="checkbox">
    <span>CHK 1</span>
</a>

where checkbox was supposed to be checked/unchecked only from server side. For reason i don't know, 'click' was not bubbling from checkbox to link, so i used js code like this:

其中复选框应该只从服务器端被选中/取消选中。出于我不知道的原因,“点击”没有从复选框冒泡到链接,所以我使用了这样的 js 代码:

$(document).on('click', '[id^="CHK_"]', function (e){
    window.open($(this).parent().attr('href'), '_self');
    e.preventDefault();
});

回答by Nasta

If your child element is located inside your parent element you could also just add this CSS property

如果您的子元素位于您的父元素内,您也可以只添加此 CSS 属性

.child {
   pointer-event: none
}

so that the click directly triggersthe parent's click event listener.

以便点击直接触发父级的点击事件监听器。

This feature's support is quite good.

这个功能的支持是相当不错的