最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - have parent div clickable with clickable child div - Stack Overflow

programmeradmin1浏览0评论

How do I do something like:

<div onclick="foo1()">
    <div onclick="foo2()"></div>
</div>

When I do that and I click the child element, it still runs the foo1() function. How do I temporarily disable the parent element or something?

How do I do something like:

<div onclick="foo1()">
    <div onclick="foo2()"></div>
</div>

When I do that and I click the child element, it still runs the foo1() function. How do I temporarily disable the parent element or something?

Share Improve this question edited Feb 1, 2015 at 18:24 Deduplicator 45.8k7 gold badges72 silver badges123 bronze badges asked Aug 5, 2013 at 2:19 Thomas LaiThomas Lai 3171 gold badge6 silver badges16 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 3

With jQuery, you can use this: http://api.jquery./event.stopPropagation/

I have created a working EXAMPLE for you

HTML

<div id="parent">
    <div id="child"></div>
</div>

CSS (just to distinguish the two divs)

#parent {
    background-color: black;
    width: 220px;
    height: 220px;
}

#child {
    position:relative;
    background-color: blue;
    width: 110px;
    height: 110px;
    top:160px;
    left:160px;
}

JavaScript ( include jQuery )

$(document).ready(function(){
    $('#child').click(function() {
        alert('Child');
        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
    });
    $('#parent').click(function() {
        alert('Parent');
    });
});

When you click on the child ONLY the action from the child is getting actioned. You can modify my example as you like to achieve what you need.

Hope this works for you.

Yes, jQuery can solve your problem. See the code below:

<script src="jquery.js" type="text/javascript"></script>
<script>
function a()
{
    alert('parent');
}

$(document).ready(function(){
    $('#div2').click(function(e){alert('child');e.stopPropagation();})
})
</script>
<div onclick="a();" style="height:100px;width:100px;border:1px solid red">
    <div id="div2" style="height:85px;width:85px;border:1px solid green">
    </div>
</div>

You can try

<div onclick="foo1(event)">
    parent
    <div onclick="foo2(event)">child</div>
</div>

And

function foo1(e){
    console.log('foo1', e)
}

function foo2(e){
    e.stopPropagation();
    console.log('foo2', e)
}

Demo: Fiddle

发布评论

评论列表(0)

  1. 暂无评论