简体   繁体   English

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

[英]trigger parent click event when child is clicked

I'n new to javaScript and jQuery. 我是javaScript和jQuery的新手。 How is this possible to call the click event of parent element when you click its child? 当您单击父元素的子元素时,如何调用它的click事件? I have this structure in my code: 我的代码中有以下结构:

<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. 编辑:在我的ul点击功能中,我需要ul id属性。 something like this: 像这样的东西:

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

so when link is clicked, event.target isn't ul element. 因此,当单击链接时,event.target不是ul元素。

You dont need to trigger element click events when child elements are clicked, the click event bubbles up the dom tree if you dont stop propagation . 单击子元素时无需触发元素单击事件,如果不停止传播 ,则单击事件会在dom树上bubbles

Here you can see it working: jsfiddle just 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 如果您单击它会起泡,这应该可以工作

You should read about event propagation in jQuery. 您应该阅读有关jQuery中事件传播的信息。 In few words: when user clicks on a then event will be propagated up in DOM tree. 在几句话:当用户点击a那么事件将在DOM树中向上传播。

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: 由于我不知道的原因,'click'不会从复选框链接到冒泡,所以我使用了如下的js代码:

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

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 triggers the parent's click event listener. 这样点击即可直接触发父级的点击事件监听器。

This feature's support is quite good . 该功能的支持相当不错

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM