假设我正在编写一个web应用程序,并且我希望在某个函数已经在多个位置声明之后添加某些行为,而不会覆盖该函数的旧行为。在JavaScript中为函数添加行为?
下面是一些简单的代码(注意window.onmousedown功能
var createMenu = function(){
var menu = document.createElement('ul');
/* add things to the menu */
window.onmousedown = function(e){
menu.style.background = "red";
}
}
var createSidebar = function(){
var sidebar = document.createElement('div');
/* add things to the sidebar */
window.onmousedown = function(e){
sidebar.id = "clicked";
}
}
var createMenu();
var createSidebar();
在这种情况下,window.onmousedown不会做两件事,它的意思做的事情 - 它在createSidebar定义将是否有一种标准的方式来实现windows.onmousedown将保留两种行为的行为?
是,不要使用直列事件*。请参阅'addEventListener'和(对于IE)'attachEvent',或者,更容易.. jQuery [或您选择的框架] :) – 2012-07-13 22:13:16