我正在使用用户的按键事件创建 Chrome 扩展程序。 但我想提醒用户该元素是否已绑定(bind)到键盘事件。
如何检测按键事件是否已绑定(bind)?
最佳答案
这很棘手。事实上,您可以通过多种不同的方式绑定(bind)到 HTMLElement 的事件。我想最简单的绑定(bind)方法(并检查是否绑定(bind)了某些东西)是这样的:
var ele = document.getElementById("yourDiv");
if (ele.onkeydown) {
alert("onkeydown event is already bound");
}
else {
ele.onkeydown = yourEventHandler;
}
问题是,正如本文评论部分所问的那样,如果您没有能力在之前更改 HTML 元素的原型(prototype),则没有真正的方法可以使用programattic javascript 检测 addEventListener 或 AttachEvent 添加的事件事件是绑定(bind)的。 (因此,用户脚本在事件绑定(bind)之前无法真正更改原型(prototype),因为它是在页面上的所有脚本完成之后运行的)。但是,如果这是您自己的页面,并且您只想监视这些事件更改。您可以通过执行以下操作将其侵入原型(prototype):
// cache the original event handler
HTMLAnchorElement.prototype.realAddEventListener = HTMLAnchorElement.prototype.addEventListener;
// now override it so you can add in your custom functionality
HTMLAnchorElement.prototype.addEventListener = function(a,b,c){
this.realAddEventListener(a,b,c);
// do whatever you want to cache those listening functions, maybe shove them in an array
// for the current object
if (!this.listeners) {
this.listeners = new Array();
}
this.listeners.push({a : a, b : b , c : c});
};
// code here that adds an event handler
document.getElementById("txtField").addEventListener("keydown", function() {
console.log("key down pressed");
});
// find the event listeners that are bound
var listeners = document.getElementById("pressed").listeners;
看,我在这里发现了这个问题,它也涵盖了这个确切的问题,其中一些很好的答案很深入:How to find event listeners on a DOM node when debugging or from the JavaScript code?
关于javascript - 如何检测键盘事件已经绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8514299/