可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a div which I have attached an onclick
event to. in this div there is a tag with a link. When I click the link the onclick
event from the div is also triggered. How can i disable this so that if the link is clicked on the div onclick
is not fired?
script:
$(document).ready(function(){ $(".header").bind("click", function(){ $(this).children(".children").toggle(); }); })
html code:
回答1:
Do this:
$(document).ready(function(){ $(".header").click(function(){ $(this).children(".children").toggle(); }); $(".header a").click(function(e) { e.stopPropagation(); }); });
If you want to read more on .stopPropagation(), look here.
回答2:
Or, rather than having an extra event handler to prevent another handler, you can use the Event Object argument passed to your click event handler to determine whether a child was clicked. target
will be the clicked element and currentTarget
will be the .header div:
$(".header").click(function(e){ //Do nothing if .header was not directly clicked if(e.target !== e.currentTarget) return; $(this).children(".children").toggle(); });
回答3:
Better way by using on() with chaining like,
$(document).ready(function(){ $(".header").on('click',function(){ $(this).children(".children").toggle(); }).on('click','a',function(e) { e.stopPropagation(); }); });
回答4:
The answers here took the OP's question too literally. How can these answers be expanded into a scenario where there are MANY child elements, not just a single
tag? Here's one way.
Let's say you have a photo gallery with a blacked out background and the photos centered in the browser. When you click the black background (but not anything inside of it) you want the overlay to close.
Here's some possible HTML:
And here's how the JavaScript would work:
$('.gallery').click( function() { $(this).hide(); } ); $('.gallery > .contents').click( function(e) { e.stopPropagation(); } );
This will stop the click events from elements inside .contents
from every research .gallery
so the gallery will close only when you click in the faded black background area, but not when you click in the content area. This can be applied to many different scenarios.
回答5:
A more short way to do it:
$('.header').on('click', function () { $(this).children('a').on('click', function(e) { e.stopPropagation(); $(this).siblings('.children').toggle(); }); });
回答6:
Or this:
$(document).ready(function(){ $(".header").click(function(){ $(this).children(".children").toggle(); }); $(".header a").click(function(e) { return false; }); });
回答7:
I stumbled upon this question, looking for another answer.
I wanted to prevent all children from triggering the parent.
This is the easiest, most readable method for that:
$(".parent").click(function() { // Do something }).children().on("click", function(e) { e.stopPropagation(); });