将事件处理程序附加到预先存在的点击事件

将事件处理程序附加到预先存在的点击事件

本文介绍了jQuery - 将事件处理程序附加到预先存在的点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个已经定义的点击事件。我想知道最好的方法是在不触摸这个代码的情况下附加另一个事件处理程序(如果可能的话)。



有没有办法将已经定义的点击事件追加另一个事件处理程序?



这是当前点击事件定义:

  $(.HwYesButton,#HwQuizQuestions)
.append(< ; a href ='javascript:void(0);'rel ='。HwYesButton'>是< / a>)
.click(function(event){
var button = $ ).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;
});


解决方案

你唯一可以做的是附加另一个另外)处理程序:

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

jQuery将按照它们附加到元素的顺序调用处理程序。 >

您不能扩展已经定义的处理程序。






Btw。你的表述有点不精确。您没有定义点击事件。您只需附加点击事件处理程序 。当用户点击某个元素时,点击事件由浏览器生成。



您可以为一个元素提供任意多的点击处理程序。也许你习惯了这个简单的JavaScript:

  element.onclick = function(){} 

使用此方法,您只能附加一个处理程序。但是,我认为jQuery会使用。


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;
        });
解决方案

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.

这篇关于jQuery - 将事件处理程序附加到预先存在的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:38