onclick事件的顺序

Nic*_*coF 6 jquery events onclick

我想向已经有onclick事件的href添加一个jquery click事件.在下面的示例中,将首先触发硬编码的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>
Run Code Online (Sandbox Code Playgroud)

RoT*_*oRa 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);
  }
})();
Run Code Online (Sandbox Code Playgroud)