Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

javascript - Insert a JQuery click handler that executes before the ones already registered

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');".

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

Jquery prepend click handler

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

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. ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...