父母和孩子中的点击事件 [英] Click event in parent and children

查看:73
本文介绍了父母和孩子中的点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有子div元素的父元素DIV.对于父级及其子级,我有单独的点击实现.

I have a parent element DIV that has children div elements. I have separate click implementations for parent and its children.

<div id="mainContainer">

    <div id="childContainer">    
    </div>

     <div id="childContainer2"> 
    </div>

</div>

$('#mainContainer').click(function () {

        console.log('main container');

    }).children().click(function () {
        console.log('childen');
        return false;
    });

    $('#childContainer2').click(function () {

        console.log('child container 2');

    }); 

这很好.但是如果我单击一个孩子,则该事件将运行两次,这应该是这样的.我的问题是-有没有一种方法可以将事件显式地写入父级,而不会影响子级,从而使子级不需要两次执行click函数?

This is working fine. but if I click a child then the event runs twice which is how it is supposed to work. My question is - Is there a way that I can explicitly write event to parent that would not affect children so that children need not execute click function twice?

推荐答案

是的,您可以更改绑定事件的顺序并停止传播,请使用

yes you can just, change the order of binding the events and to stop propagation use stopImmediatePropagation

考虑此小提琴

$('#childContainer2').click(function (e) {       
       alert('child container 2'); 
        e.stopImmediatePropagation()
     return false;
    }); 
$('#mainContainer').click(function () {
alert('main container');

    }).children().click(function (e) {
       alert('childen');
        return false;
    });

这篇关于父母和孩子中的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆