Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

javascript - How can I stop an onclick event from firing for parent element when child is clicked?

I'm having two issues with onclick events, they are somewhat similar so I'll ask them both here.

First:

I have a checkbox in a div. The input has an onchange function and the div has an onclick function.

<div onclick="doSomething()">
     <input type="checkbox" onchange="doSomethingElse()" />
</div>

The problem is when I check/uncheck the checkbox both doSomething() and doSomethingElse() fire. Any ideas of how to stop this from occuring? I've tried doing onchange="doSomethingElse(event)" and the in doSomethingElse(e) function I had e.stopPropagation(); and this did not work.

Second:

I have an image in a div. The div has an onclick function but the image does not. The image is, purposely, larger than the div and overflows outside the div.

-----------------------
|        image        |
|   ---------------   |
|   |     div     |   |
|   |             |   |
|   ---------------   |
|                     |
-----------------------

I only want the onclick to fire if the user clicks within the bounds of the div box. However, the onclick event also fires if you click on a part of the image that has overflowed to the outside of the div... Any ideas?

The first question is more important to me than the second. But if someone can answer both that would be awesome!

Thanks in advance for your help,
Matt

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For your first question: IE doesn't support stopPropagation(), instead you should use e.cancelBubble = true. Just do a function check first to find out which method you should use (if (e.stopPropagation) {code}).

For your second question: Maybe include a second div that handles the click event?

<div><img src="image.jpg"/></div>
<div style="position:absolute" onclick="doSomething();"></div>

and then position the second div correctly


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...