(我昨天问过类似的问题,但它朝另一个方向发展,所以再次发布更多详细信息)
我有一个使用html元素ID的类/对象,然后在该元素上设置事件处理程序。
like: batman.on("click",run_this_code());
其结果显然是在触发元素click事件时运行func /代码。
现在,我的问题是:如何收听/观看其他元素事件? 说蝙蝠侠是
batman.listen("click","fired on element with ID superman",run_this_code());
我想出的唯一一件事是,我不知道100%如何做:用以下方法注册对文档的所有点击:
var arr;
document.addEventListener('click', function (event) {
if (!event.target.hasAttribute('track_me')) return;
// code here that saves the click, and the ID, into an array (arr)
}, false);
现在其他实例可以以某种方式检查阵列上的变化(arr),并做出相应的反应。
好好逛逛,基本上我该怎么办:
batman.listen("click","on_superman",function(){
alert("this instance represents the 'batman' element, but the element 'superman' was just clicked.");
}
);
我不想在“超人”实例中编写代码。这只是一个例子,我想成为我的类的通用函数,以侦听其他实例上的事件。
答案 0 :(得分:0)
假设batman
是<button id="batman">
,而superman
是文本字段<input type="text" id="superman">
,并且对于按钮“蝙蝠侠”,我有一个如上所述的类实例。在那种情况下,我将如何收听“超人”事件
您可以像这样获得对superman
元素的引用:
document.getElementById("superman")
或者,如果您使用的是jQuery,您可能会得到一个包含该元素的jQuery对象,如下所示:
$("#superman")
然后使用addEventListener
(在元素上)或on
(在jQuery对象上)侦听click
事件。
document.getElementById("superman").addEventListener("click", function() {
// superman clicked
});
或
$("#superman").on("click", function() {
// superman clicked
});
执行此操作的代码可以在所需的任何类或对象方法中。
在评论中您说过:
我的目标是具有对任何其他元素事件做出反应的功能
您可能正在寻找事件委托:大多数事件 bubble ,因此您可以将事件侦听器放置在某个容器(如果需要,document
本身)上,并监视事件发生。触发事件的元素可以作为您的处理程序收到的事件对象的target
属性来使用:
document.addEventListener("click", function(e) {
// Use `e.target` here...
});
示例:
document.addEventListener("click", function(e) {
console.log(e.target.id + " click");
});
document.addEventListener("input", function(e) {
console.log(e.target.id + " input: " + e.target.value);
});
<div>
<input id="one" type="text">
</div>
<div>
<input id="two" type="text">
</div>