【问题标题】:order of onclick eventsonclick 事件的顺序
【发布时间】:2010-05-06 12:54:18
【问题描述】:

我想向已经有 onclick 事件的 href 添加一个 jquery 点击事件。 在下面的示例中,硬编码的 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>

【问题讨论】:

    标签: jquery events onclick


    【解决方案1】:

    您需要获取原始事件处理程序,将其替换为您自己的事件处理程序,然后调用原始处理程序,但是我不确定这是否可以使用 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);
      }
    })();
    

    【讨论】:

    • 有时,您需要在旧函数中保留this 变量,因此解决方案是使用oldOnClick.call(link, e)
    【解决方案2】:
       $(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);
                    });
                });
            });
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-12
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多