Javascript 将多个事件绑定到一个侦听器(没有 JQuery)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8796988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding multiple events to a listener (without JQuery)?
提问by johnkreitlow
While working with browser events, I've started incorporating Safari's touchEvents for mobile devices. I find that addEventListener
s are stacking up with conditionals. This project can't use JQuery.
在处理浏览器事件时,我已经开始为移动设备整合 Safari 的 touchEvents。我发现addEventListener
s 与条件叠加在一起。这个项目不能使用JQuery。
A standard event listener:
标准事件侦听器:
/* option 1 */
window.addEventListener('mousemove', this.mouseMoveHandler, false);
window.addEventListener('touchmove', this.mouseMoveHandler, false);
/* option 2, only enables the required event */
var isTouchEnabled = window.Touch || false;
window.addEventListener(isTouchEnabled ? 'touchmove' : 'mousemove', this.mouseMoveHandler, false);
JQuery's bind
allows multiple events, like so:
JQuerybind
允许多个事件,如下所示:
$(window).bind('mousemove touchmove', function(e) {
//do something;
});
Is there a way to combine the two event listeners as in the JQuery example?ex:
有没有办法像 JQuery 示例中那样组合两个事件侦听器?前任:
window.addEventListener('mousemove touchmove', this.mouseMoveHandler, false);
Any suggestions or tips are appreciated!
任何建议或提示表示赞赏!
采纳答案by RobG
In POJS, you add one listener at a time. It is not common to add the same listener for two different events on the same element. You could write your own small function to do the job, e.g.:
在 POJS 中,您一次添加一个侦听器。为同一元素上的两个不同事件添加相同的侦听器并不常见。您可以编写自己的小函数来完成这项工作,例如:
/* Add one or more listeners to an element
** @param {DOMElement} element - DOM element to add listeners to
** @param {string} eventNames - space separated list of event names, e.g. 'click change'
** @param {Function} listener - function to attach for each event as a listener
*/
function addListenerMulti(element, eventNames, listener) {
var events = eventNames.split(' ');
for (var i=0, iLen=events.length; i<iLen; i++) {
element.addEventListener(events[i], listener, false);
}
}
addListenerMulti(window, 'mousemove touchmove', function(){…});
Hopefully it shows the concept.
希望它显示了这个概念。
Edit 2016-02-25
编辑 2016-02-25
Dalgard's comment caused me to revisit this. I guess adding the same listener for multiple events on the one element is more common now to cover the various interface types in use, and Isaac's answer offers a good use of built–in methods to reduce the code (though less code is, of itself, not necessarily a bonus). Extended with ECMAScript 2015 arrow functions gives:
Dalgard 的评论使我重新审视了这一点。我想在一个元素上为多个事件添加相同的侦听器现在更常见以涵盖使用的各种接口类型,并且 Isaac 的答案很好地利用了内置方法来减少代码(尽管代码较少,但它本身,不一定是奖金)。使用 ECMAScript 2015 箭头函数扩展提供:
function addListenerMulti(el, s, fn) {
s.split(' ').forEach(e => el.addEventListener(e, fn, false));
}
A similar strategy could add the same listener to multiple elements, but the need to do that might be an indicator for event delegation.
类似的策略可以向多个元素添加相同的侦听器,但这样做的需要可能是事件委托的一个指标。
回答by Isaac
Some compact syntax that achieves the desired result, POJS:
一些达到预期结果的紧凑语法,POJS:
"mousemove touchmove".split(" ").forEach(function(e){
window.addEventListener(e,mouseMoveHandler,false);
});
回答by pmrotule
Cleaning up Isaac's answer:
清理以撒的回答:
['mousemove', 'touchmove'].forEach(function(e) {
window.addEventListener(e, mouseMoveHandler);
});
EDIT
编辑
ES6 helper function:
ES6 辅助函数:
function addMultipleEventListener(element, events, handler) {
events.forEach(e => element.addEventListener(e, handler))
}
回答by user3796876
For me; this code works fine and is the shortest code to handle multiple events with same (inline) functions.
为了我; 这段代码工作正常,是处理具有相同(内联)函数的多个事件的最短代码。
var eventList = ["change", "keyup", "paste", "input", "propertychange", "..."];
for(event of eventList) {
element.addEventListener(event, function() {
// your function body...
console.log("you inserted things by paste or typing etc.");
});
}
回答by ChrisTheButcher
ES2015:
ES2015:
let el = document.getElementById("el");
let handler =()=> console.log("changed");
['change', 'keyup', 'cut'].forEach(event => el.addEventListener(event, handler));
回答by ChrisTheButcher
I have a simpler solution for you:
我为您提供了一个更简单的解决方案:
window.onload = window.onresize = (event) => {
//Your Code Here
}
I've tested this an it works great, on the plus side it's compact and uncomplicated like the other examples here.
我已经测试过它,它工作得很好,从好的方面来说,它像这里的其他示例一样紧凑且简单。
回答by Selvakumar Arumugam
AddEventListenertake a simple string that represents event.type. So You need to write a custom function to iterate over multiple events.
AddEventListener采用一个简单的字符串来表示event.type。所以你需要编写一个自定义函数来迭代多个事件。
This is being handled in jQuery by using .split(" ") and then iterating over the list to set the eventListeners for each types
.
这是通过使用 .split(" ") 在 jQuery 中处理的,然后遍历列表以设置每个types
.
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native events in IE.
eventHandle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) { <-- iterates thru 1 by 1
回答by Reza Saadati
One way how to do it:
一种方法如何做到这一点:
const troll = document.getElementById('troll');
['mousedown', 'mouseup'].forEach(type => {
if (type === 'mousedown') {
troll.addEventListener(type, () => console.log('Mouse is down'));
}
else if (type === 'mouseup') {
troll.addEventListener(type, () => console.log('Mouse is up'));
}
});
img {
width: 100px;
cursor: pointer;
}
<div id="troll">
<img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">
</div>