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

How do I do something like:<div onclick="foo1()"><div onclick="foo2()">

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745180797a4615408.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信