2012-10-18 6 views
0

jQuery 튜토리얼을 시작하고 jQuery 애니메이션의로드 순서에 대한 기본적인 질문이 있습니다. 그러나jquery 애니메이션의로드 순서

<body> 
    <a href="http://jquery.com/">jQuery</a> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> 
    <script> 
    $(document).ready(function(){ 
     $("a").click(function(event){ 
     alert("As you can see, the link no longer took you to jquery.com"); 
     event.preventDefault(); 
     }); 
     $("a").click(function(event){ 
     event.preventDefault(); 
     $(this).hide("slow"); 
     }); 
    }); 
    </script> 
</body> 

내가 그렇게 document.ready 함수에서 두 번째 클릭 기능을 때 : 나는 다음과 같은 HTML 코드를 사용하는 경우 경고 및 숨기기 애니메이션을 모두 표시하도록하는 링크를 클릭

코드가 아래처럼 보이면 팝업이 나타나고 텍스트는 사라지지만 숨기기 애니메이션이 발생하지 않습니다.

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>jQuery demo</title> 
    <style> 
    a.test { font-weight: bold; } 
    </style> 
</head> 
<body> 
    <a href="http://jquery.com/">jQuery</a> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> 
    <script> 
    $(document).ready(function(){ 
     $("a").click(function(event){ 
     alert("As you can see, the link no longer took you to jquery.com"); 
     event.preventDefault(); 
     }); 
    }); 
    $("a").click(function(event){ 
     event.preventDefault(); 
     $(this).hide("slow"); 
    }); 
    </script> 
</body> 
</html> 

왜 숨기기 애니메이션이 첫 번째 예만 표시되고 두 번째 표시가 아닌지 설명 할 수 있습니까?

답변

0

두 번째 핸들러가 div의 모든 앵커 <a> 태그에 첨부되지 않기 때문입니다.

$("a").click(function(event){ //This function will execute as the script loads 
           // and during this time, DOM might have been loaded yet 
    event.preventDefault(); 
    $(this).hide("slow"); 
}); 

그러나이 내부를 포장하여.

$(document).ready(function() { 

    // DOM is loaded 

}); 

먼저 DOM이로드되었는지 확인한 다음 처리기를 첨부하십시오.

1

두 번째 예에서는 click()에 대한 마지막 호출이 ready 처리기 외부에 있기 때문입니다.

호출이 수행 될 때 DOM이 아직 준비되지 않았으므로 처리기가 바인딩되지 않고 나중에 애니메이션이 수행되지 않습니다.

+0

DOM이 무엇인지, 핸들러 바인딩이 어떻게 작동하는지 더 자세히 살펴 보겠습니다. –