2010-05-06 67 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。下面是使用jQuery只訪問元素,然後 「正常」 JavaScript設置處理程序的一個示例:

// 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

有時,你需要在舊函數中保留'this'變量,所以解決方案是'oldOnClick.call(link,e)'。 – TautrimasPajarskas 2013-08-20 12:32:49

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); 
       }); 
      }); 
     }); 
    });