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
256 views
in Technique[技术] by (71.8m points)

javascript - jQuery - Append an event handler to preexisting click event

I have a click event that is defined already. I was wondering what the best way would be to append another event handler to this event without touching this code (if possible).

Is there a way to just append another event handler to the already defined click event?

This is the current click event definition:

 $(".HwYesButton", "#HwQuizQuestions")
        .append("<a href='javascript:void(0);' rel='.HwYesButton'>Yes</a>")
        .click(function(event) {
            var button = $(this).parent();
            var questionId = button.attr('id');
            $iadp.decisionPoint["HwQuizYourself"].Input.inputProvided(questionId);
            button.find(".HwNoButton").removeClass("HwButtonSelected");
            $(this).addClass("HwButtonSelected");
            button.removeClass("HwQuestionSkipped");

            $iadp.flat.setBoolean(questionId, true);
            return false;
        });
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The only thing you can do is to attach another (additional) handler:

$(".HwYesButton", "#HwQuizQuestions").click(function() {
    // something else
});

jQuery will call the handlers in the order in which they have been attached to the element.

You cannot "extend" the already defined handler.


Btw. your formulation is a bit imprecise. You are not defining a click event. You are only attaching click event handlers. The click event is generated by the browser when the user clicks on some element.

You can have as many click handlers as you want for one element. Maybe you are used to this in plain JavaScript:

element.onclick = function() {}

With this method you can indeed only attach one handler. But JavaScript provides some advanced event handling methods which I assume jQuery makes use of.


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

...