通过一次调用绑定多个类的单击事件

时间:2021-05-19 23:55:22

On page load I am binding a lot of click events to different objects and code looks like this:

在页面加载时,我将大量点击事件绑定到不同的对象,代码如下所示:

$(document).on('click', '.class1', function() { ... });
$(document).on('click', '.class2', function() { ... });
$(document).on('click', '.class3', function() { ... });
...

which I find to look pretty messy. I know that with jQuery one can bind multiple different events on one DOM element:

我发现它看起来很混乱。我知道使用jQuery可以在一个DOM元素上绑定多个不同的事件:

$(document).on({
    click: function() { ... },
    mouseenter: function() { ... },
    mouseleave: function() { ... },
    ...
});

Can this be done in a similar way for multiple classes? Something like this:

对于多个类,这可以用类似的方式完成吗?像这样的东西:

$(document).on('click', {
    '.class1': func1,
    '.class2': func2,
    '.class3': func3,
    ...
});

Please note, that func1, func2, func3, etc implement different logic and cannot be combined.

请注意,func1,func2,func3等实现不同的逻辑,不能组合。

1 个解决方案

#1


4  

That syntax is not supported by jQuery. You can bind the event handlers by iterating through the object:

jQuery不支持该语法。您可以通过迭代对象来绑定事件处理程序:

var handlers = {
  '.class1': function() { ... },
  '.class2': function() { ... },
  '.class3': function() { ... },
};

Object.keys(handlers).forEach(function(sel) {
    $(document).on('click', sel, handlers[sel]);
});

You can also define a utility function:

您还可以定义实用程序功能:

/**
 * A utility function for mass event delegation
 * @param  {String|Object} parent - the target of event delegation
 * @param  {String} event - event name
 * @param  {PlainObject} handlers
 * @return {undefined}
 */
$.delegate = function(parent, event, handlers) {
  parent = $(parent);
  Object.keys(handlers).forEach(function(sel) {
    parent.on(event, sel, handlers[sel]);
  });
}

$.delegate(document, 'click', {
  '.class1': function() { ... },
  '.class2': function() { ... },
  '.class3': function() { ... },
});

#1


4  

That syntax is not supported by jQuery. You can bind the event handlers by iterating through the object:

jQuery不支持该语法。您可以通过迭代对象来绑定事件处理程序:

var handlers = {
  '.class1': function() { ... },
  '.class2': function() { ... },
  '.class3': function() { ... },
};

Object.keys(handlers).forEach(function(sel) {
    $(document).on('click', sel, handlers[sel]);
});

You can also define a utility function:

您还可以定义实用程序功能:

/**
 * A utility function for mass event delegation
 * @param  {String|Object} parent - the target of event delegation
 * @param  {String} event - event name
 * @param  {PlainObject} handlers
 * @return {undefined}
 */
$.delegate = function(parent, event, handlers) {
  parent = $(parent);
  Object.keys(handlers).forEach(function(sel) {
    parent.on(event, sel, handlers[sel]);
  });
}

$.delegate(document, 'click', {
  '.class1': function() { ... },
  '.class2': function() { ... },
  '.class3': function() { ... },
});