문제

HTML

<div class="mybox" id="element1">
    <div class="mybox" id="element2">
        <div class="mybox" id="element3">
        </div>
        <div class="mybox" id="element4">
        </div>
    </div>
</div>

JS

$(".mybox").live("mouseup", function(event) {
   alert($(this).attr("id"));
});

Okay, so my question is how to get only the active div (the one that I have clicked on, not all the parents). When I click on element2 I get element2 & then "element1" active, when I click on element3 I get element2 & then element1 active again, etc.

Any suggestions?

도움이 되었습니까?

해결책

The reason you see all those alerts is due to event bubbling. Each time you click on an element, the event is propagated up the chain. Every element which has a click event attached along the way will be executed.

To ensure you only execute the code when the current element has been clicked on and to ignore bubbled events change your event to check if that the current element is the one you clicked on using event.target and only then execute your intended code:

$(".mybox").live("mouseup", function(event) {
    if(event.target === this){
       alert($(this).attr("id"));
    }
});​

DEMO - using live

If you are using jQuery 1.7 or later live() was deprecated and on() is now the preferred way of attaching and removing events.

To use on() instead you can do this:

(document).on("mouseup", ".mybox", function(event) {
    if (event.target === this) {
        alert($(this).attr("id"));
    }
});​

DEMO - using on()

When using on() you specify the closest static element which in the example above is the document. However, if you have a closer static element you should be using that instead of document.

I have linked all the required documentation in the answer but to summarise again.

Resources

  • live() - has all the details on why it has been deprecated
  • on() - preferred since 1.7
  • delegate() - which can be used instead of live since 1.4.2 or later

다른 팁

As Francois wrote the effect is called "event bubbling". But jquery has it's own function to prevent the event to go up the chain: stopPropagation

$("p").click(function(event){
  event.stopPropagation();
  // do something
}); 

Only if this fails to work for your special case, you should use the solution of comparing event targets.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top