Hijacking onchange event without interfering with original function

我的未来我决定 提交于 2019-12-01 01:03:36

If I'm correct it sounds like you want to inject new code into an existing event. This may help you if you want a pure JavaScript solution and here is a fiddle demonstrating the feature. http://jsfiddle.net/VZCve/1/

var element = document.getElementById("myElementId");

element.onchange = (function (onchange) {
  return function(evt) {
    // reference to event to pass argument properly
    evt  = evt || event;

    // if an existing event already existed then execute it.
    if (onchange) {
      onchange(evt);
    }

    // new code "injection"
    alert("hello2");
  }
})(element.onchange);

EDITED: Now that the tags are changed and you are reference jQuery in your Question

jQuery will continue to bind new functions using jQuery.change().

note the following will execute all change functions assigned

$(document).ready(function () {
  $("#myElement").change(function() { alert('executed') });
  $("#myElement").change(function() { alert('executed again') });
  $("#myElement").change(function() { alert('executed again again') });
});

When you trigger the change event for the element in the selector you will receive 3 alerts.

Note the order of the events firing is dependent on the order each function was bound to the element.

Here is a simple fiddle demonstrating the functionality in jQuery http://jsfiddle.net/VZCve/

Using jQuery's .change() function to assign an onchange handler will not override existing onchange events (or other jQuery-assigned handlers). See a working demonstration here: http://jsfiddle.net/nrabinowitz/EyKdm/

borrel

Newer browsers have an addEventListener which can do it but dean.edwards solution is better

is more compatible with older browsers

you could also use a costem eventhandeler(s) whitch call array's of functions (done properly you could handle the return value of the sub-functions to decide if you want to run the next function, also couts for event

if(typeof element.onclickfunctions == "undefined"){
  element.onclickfunctions = [];
}
element.onclickfunctions.push( function(event){return Myfunct(event);});//or var
element.onclick = function(event){
  for(x in element.onclickfuncitons){
    if(! x(event)){
      break;
    }
  }
};

code not tested please comment before downvote

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!