插入在已注册的处理程序之前执行的JQuery单击处理程序 [英] Insert a JQuery click handler that executes before the ones already registered

查看:74
本文介绍了插入在已注册的处理程序之前执行的JQuery单击处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序的所有页面上为每个(Button,Anchor,Select)附加一个click事件处理程序,该处理程序应该在已经在html中声明的已连接处理程序之前运行,如 onclick =返回SomeFunction('a','b');

I want to attach a click event handler to each and every (Button, Anchor, Select) on all pages in my application, and that handler should run before the already attached handlers declared in html like onclick="return SomeFunction('a','b');".

我在stackoverflow上发现了一个关于前置处理程序的问题,这正是我想要的,问题的链接是: -

I found a question on stackoverflow for prepending handlers, and that was what I wanted exactly, the link to the question is:-

Jquery前置点击处理程序

但是,上面的代码不起作用,我怀疑它是否适用于提问者。我根据我的要求编写的代码是: -

But, the above code is not working, I doubt if it worked for the asker or not. The code I have written according to my requirements is:-

<input type="button" value="Click 1" onclick="f2();" />

$(document).ready(function() {
            $("input[type=button]").each(function() {

                // your button
                var btn = $(this);

                // original click handler
                var clickhandler = btn.attr("onclick");
                btn.attr("onclick", "return false;");


                // new click handler
                btn.click(function() {
                    alert('Prepended Handler');
                    clickhandler();
                });
            });
        });

        function f2() {
            alert('Handler declared in HTML');
        }

此代码的输出应为:显示Prepended Handler的警报然后显示以HTML格式声明的处理程序的下一个警告。

The output for this code should have been: An alert showing "Prepended Handler" and then a next alert showing "Handler declared in HTML".

但实际结果是:只显示第一个警报而第二个警报不显示。

But, the actual result is: Only the first alert is appearing and the second one is not.

如果您在此代码中发现任何问题,请告诉我。

Please tell me if you see any problem in this code.

而且,如何做到这一点。 ?

And, how can this be done. ?

推荐答案

这应该重新排列您的点击处理程序。

This should rearrange your click handlers.

$(document).ready(function() {
    $("input[type=button]").each(function() {

        // your button
        var btn = $(this);

        var clickhandler = this.onclick;
        this.onclick = null;


        // new click handler
        btn.click(function() {
            alert('Prepended Handler');
        });
        btn.click(clickhandler);
    });
});

function f2() {
alert('Handler declared in HTML');
}

这篇关于插入在已注册的处理程序之前执行的JQuery单击处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆