2012-05-18 5 views
4
을 포기하지 않을

내가 DIV ID를 클릭하면 내 코드event.target이 원하는 출력

<div id="hello"> 
<div>A</div></div> 
<script> 
$(function(){ 
$(document).mousedown(function(event){alert(event.target.id);}); 
});</script> 

지금은 센터 DIV의 ID를 취하고로 "안녕하세요"가 null의 경고입니다하지만 난 외부의 ID를 원하는 div. 어떻게 달성 될 수 있습니까? 사용 event.target.parentNode.id

+0

'A'를 클릭하면 부모의 ID가 출력되는 이유는 무엇이라고 생각하십니까? 또는 다른 곳을 클릭하면 # hello의 ID가 출력됩니까? – gabitzish

+0

이벤트 캡처 및 버블 링. http://www.quirksmode.org/js/events_order.html – mossimokim

답변

0

대상이

try this instead 가장 안쪽 DIV 이었기 때문에 :

event.target.parentNode.id 
+0

+1 정답은 –

1

하는 약간의 코드를 변경해보십시오 :

<div id="hello"> 
<div>A</div></div> 
<script> 

$(function(){ 
    //You can change the selector to what suits you best here 
    $("body>div").mousedown(function(event){alert(event.currentTarget.id);}); 

    //it is safer to use currentTarget when you have nested elements 
});</script> 
+0

입니다.이 솔루션을 읽은 곳에서 –

+0

코드가 약간 변경되었습니다. 귀하의 코드에서 모든 div에 이벤트 리스너를 첨부하고 있지만 귀하의 의도는 id를 사용하여 div에 연결하는 것입니다. 귀하의 경우에는 'body'의 자식이지만 최종 코드에 따라 다를 수 있습니다. ... – strah

+0

http://api.jquery.com/event.currentTarget/ –

0

당신은에 이벤트를 바인딩해야 div에 관심이 있습니다. 귀하의 경우, 당신은 uld에 바인딩 $('#hello')

여러 개의 div가있는 경우 해당 이벤트를 바인드하고 클래스를 추가 한 다음 해당 mousedown 이벤트를 해당 클래스에 바인딩하고 콜백 함수에서 event.target의 ID를 확인합니다.