I realized event.target redundancy could cause a lot of problems in the future when they are binded with another event in the next level.
For example, when i have an Div element inside another.
<div id='div1'>
<div id='div2>
</div>
</div>
I use the follow Jquery code to bind an event.
$('div').bind('click', function(event){
alert(event.target.id)
}
There are two alert boxes instead of one. I understand the concept of why is because there are 2 divs I am clicking.
Of course the problem in a deeper level is that when I am trying to bind an event after this event accordingly with the event.target, it binds x2 so on and so forth.
Is it possible to get rid of the even开发者_如何转开发t binding on the outside div and only capture the inside.
Thanks in advance.
You can prevent the event from bubbling using event.stopPropgation()
like this:
$('div').bind('click', function(event){
alert(event.target.id);
event.stopPropagation();
});
You can give it a try here. This will "trap" the click
on the first <div>
that gets it, and won't let it propagate up to any parents.
I think you just need to select the inside div in your bind call:
$('div:eq(0)').bind('click', function(event){
alert(event.target.id)
}
精彩评论