2010-05-06 7 views
6

jQuery 클릭 이벤트를 이미 onclick 이벤트가있는 href에 추가하려고합니다. 아래 예제에서 하드 코드 된 onclick 이벤트가 먼저 트리거됩니다. 어떻게 거꾸로 할 수 있습니까?onclick 이벤트 순서

<a class="whatever clickyGoal1" href="#" onclick="alert('trial game');">play trial</a> 
<br /> 
<a class="whatever clickyGoal2" href="#" onclick="alert('real game');">real trial</a> 
<p class="goal1"> 
</p> 
<p class="goal2"> 
</p> 

<script type="text/javascript"> 
    $("a.clickyGoal1").click(function() { 
     $("p.goal1").append("trial button click goal is fired");//example 
    }); 
    $("a.clickyGoal2").click(function() { 
     $("p.goal2").append("real button click goal is fired"); //example 
    });   
</script> 

답변

6

당신은 그러나 나는 그와 jQuery 가능하다면 모르겠지만, 원래의 이벤트 핸들러를 얻을 자신의로 교체 한 후 원래의 핸들러를 호출해야합니다.

// Wrapper in order not to add unnecceary variables to the global namespace 
(function(){ 
    var link = $("a.clickyGoal1")[0]; 
    var oldOnClick = link.onclick; 
    link.onclick = function(e) { 
    $("p.goal1").append("trial button click goal is fired"); 
    oldOnClick(e); 
    } 
})(); 
+0

그리고 때로는 여기에만 요소에 액세스하기 위해 다음 자바 스크립트 처리기를 "정상"설정 jQuery를 사용하는 예입니다 old 함수 내에서'this' 변수를 보존 할 필요가 있습니다. 그래서 해결책은'oldOnClick.call (link, e)'입니다. – TautrimasPajarskas

1
$(function() { 
     $("a.whatever").removeAttr('onclick').click(function(e) { 
      e.preventDefault(); 
      var text = $(this).text(); 
      var cls = this.className.split(' ')[1].split('clickyGoal')[1]; 
      $('p.goal' + cls).fadeOut(500,function() { 
       $(this).html(text+' button fired '+cls).fadeIn(500,function() { 
        alert(text); 
       }); 
      }); 
     }); 
    });