首页 > 解决方案 > 如何在 jQuery 中拆分多个事件句柄?

问题描述

试图弄清楚如何在新行中拆分多个事件以使下面的代码更清晰。

$document.find('body').on(
    'click dblclick mousedown mousemove mouseout mouseover mouseup mousewheel keydown keypress keyup textInput touchcancel touchend touchmove touchstart blur change focus reset resize select scroll submit zoom',
    testConsole
);

function testConsole() {
    console.log(' test');
}

我怎样才能使这段代码更干净?现在我有一个包含我想要处理的所有事件的单行,是否可以将它放在一个数组或其他东西中以使其可读?

标签: javascriptjqueryangularjseventsevent-handling

解决方案


array您可以使用,然后join使用创建事件space。检查下面的代码。

var events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'mousewheel', 'keydown', 'keypress', 'keyup', 'textInput', 'touchcancel', 'touchend', 'touchmove', 'touchstart', 'blur', 'change', 'focus', 'reset', 'resize', 'select', 'scroll', 'submit', 'zoom'];

events = events.join(" ");

$(document).find('body').on(events,testConsole);

function testConsole() {
    console.log(' test');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>dsdsdsd</body>


推荐阅读