在不干扰原始功能的情况下劫持onchange事件 [英] Hijacking onchange event without interfering with original function

查看:75
本文介绍了在不干扰原始功能的情况下劫持onchange事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个图书馆我希望包含在可能已经使用onchange事件的不同页面上 - 有没有办法将我的事件附加到onchange而不删除原始事件?



编辑:



在窗口obj上的onchange。不仅是一个单独的元素 - 在网址中更改哈希变化等等。抱歉,如果我把它们混淆了!

解决方案

如果我这是正确的,听起来你想要将新代码注入现有事件中。如果你想要一个纯粹的JavaScript解决方案,这可能对你有所帮助,这里有一个演示该功能的小提琴。 http://jsfiddle.net/VZCve/1/

  var element = document.getElementById(myElementId); 

element.onchange =(function(onchange){
return function(evt){
//对正确传递参数的事件的引用
evt = evt || event;

//如果现有事件已经存在则执行它。
if(onchange){
onchange(evt);
}

//新代码注入
alert(hello2);
}
})(element.onchange);

已编辑:现在标签已更改且您引用了jQuery in你的问题



jQuery将继续使用 jQuery绑定新功能.change()。



请注意以下内容将执行分配的所有更改功能

  $(document).ready(function(){
$(#myElement)。change(function(){alert('executed')});
$ (#myElement)。change(function(){alert('再次执行')});
$(#myElement)。change(function(){alert('再次执行')} );
});

当您在选择器中触发元素的更改事件时,您将收到3个警报。



注意事件触发的顺序取决于每个函数绑定到元素的顺序。



这是一个简单的小提琴演示jQuery中的功能 http://jsfiddle.net/VZCve/


im writing on a library i want to include on different pages who might already use the onchange event - is there any way to attach my event to onchange without removing the original one?

EDIT:

onchange on the window obj. not only a single element - onchange as in a hash change in the url etc. sorry if i confused them!

解决方案

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/

这篇关于在不干扰原始功能的情况下劫持onchange事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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