Preventing jQuery event triggering from sub elements
I have the following code:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"
type="text/javascript">
</script>
</head>
<body>
<div id="a">
<div id="b">
<script type="text/javascript">
$('#b').bind('fuffle',function() {alert('b fuffled');})
</script>
<div id="c"></div>
</div>
</div>
</body>
</html>
When I run:
$("#b").tr开发者_StackOverflowigger('fuffle')
I get the alert box as I would expect. However, when I run:
$("#c").trigger('fuffle')
I also get the alert box. I am guessing this because c is nested in b, however, is there a technique where this behavior could be avoided.
In my code, sub elements can also trigger fuffle, but they are bound to a different method. This behavior is literally causing a JS stackoverflow error.
Try passing the event to your anonymous handler function like
...'fuffle', function(e) {alert...
then call
e.stopPropagation()
which will prevent the event bubbling. The more blunt approach is to return false.
http://api.jquery.com/event.stopPropagation/
JavaScript events bubble up the DOM. You can either:
- Check the
event.target
to see if the event originated from #c or one of its children, in the event handler bound to#c
, or - Bind an event handler to
#b
that stops the event from propagating up the DOM tree.
maybe have a simple check
$('#b').bind('fuffle',function(){
if($(this).attr("id") == "b"){
alert('b fuffled');
}
});
精彩评论