2012-06-10 4 views
2
<div id="parent"> 
    <div id="children"> 
    </div> 
    </div> 

우리가 같은 같은 이벤트와 부모와 자녀 모두를 결합하는 경우 :이벤트 바인딩 문제

 $("#parent").live({ mouseenter : Infocus , mouseleave : Outfocus }); 
    $("#children").live({ mouseenter : Infocus , mouseleave : Outfocus }); 

내가 부모도 강조 아이들을 통해 내 마우스를 얻을 때 이제 내 문제는, 아무도 나에게 여기에 무슨 일이 일어나는지 말해 줄 수 있니?

답변

2

이벤트 방지를 위해 stopPropagation()을 사용해야합니다.

function Infocus(e) { 
    e.stopPropagation(); 
    // your code 
} 

function Outfocus(e) { 
    e.stopPropagation(); 
    // your code 
} 

읽기에 대한 .stopPropagation()

당신이 뭔가를 할 수 있습니다 : 다른 대답이 정확하더라도 (만족스럽지 않을 수 있음)

$("#parent").live({ 
    mouseenter: Infocus, 
    mouseleave: Outfocus 
}); 
$("#children").live({ 
    mouseenter: Infocus, 
    mouseleave: Outfocus 
}); 

function Infocus(e) { 
    if(this.id == 'parent') { 
     $(this).css('background', 'yellow'); 
    } else if(this.id == 'children') { 
     $(this).css('background', 'green'); 
     $(this).parent().trigger('mouseleave') 
    } 
} 

function Outfocus(e) { 
    if(this.id == 'parent') { 
     $(this).css('background', 'transparent'); 
    } else if(this.id == 'children') { 
     $(this).css('background', 'transparent'); 
     $(this).parent().trigger('mouseenter') 
    } 
} 

DEMO

2

어떤 의미에서. 네 문제가 또 다른 것 같아. 내가 생각하는 것은 mouseenter에 강조 표시하고 mouseleave에 강조 표시를 제거하지만 실제로 일어나고있는 것은 다릅니다.

#children 위로 이동할 때 #parent을 떠나지 마십시오.

   +-----------------------------------+ 
       |#parent       | 
       |         | 
       |         | 
       |   +-------------+   | 
       |   |#children |   | 
       |   |    |   | 
      (1) | (2) |  (3)  | (4) | (5) 
       |   |    |   | 
       |   |    |   | 
       |   +-------------+   | 
       |         | 
       |         | 
       |         | 
       +-----------------------------------+ 
  1. 아무것도 : 당신이 바로 (5) 왼쪽 (1)에서 마우스를 이동하면 이미지에서 이러한 트리거 이벤트입니다.
  2. #parent.mouseleave

이 경우

  • #children.mouseleave
  • #children.mouseenter
  • #parent.mouseenter
  • 는 당신은 당신 강조 논리를 수정해야합니다.