目前,我有一个缓存变量$this,我正在应用.on来响应各种可能的行为触发器类型. $this.on('click','.trigger a',rowTrigger);$this.on('click','.actions nav a',rowAction); 在jQuery .on Documentation中没有提到是否有办
$this.on('click','.trigger a',rowTrigger); $this.on('click','.actions nav a',rowAction);
在jQuery .on Documentation中没有提到是否有办法将上述两个组合成一个单独的呼叫.例如,像这样的东西可能会很好:
$this.onAny({ click: [ {'.trigger a':rowTrigger}, {'.actions nav a':rowAction} ] });
有没有办法实现这种声明(例如现有插件扩展.on)?
UPDATE
用例(在当前代码中,在一个很好的解决方案之前):
// Plugin 1: function addTriggers(){ $this.find('td:last').append('<span class="trigger"><a href="#"></a></span>'); return {selector:'.trigger a', event:'click', target: $this, callback: rowTrigger}; } // Plugin 2: function addInlineNavigation(){ $navCode = '...' $this.find('td:last').append('<div class="actions">'+$navCode.html()+'</div>'); return {selector:'.actions nav a', event:'click', target: $this, callback: rowAction}; }
Is there a way to achieve this kind of statement (e.g. an existing plugin to extend
.on
)?
我不知道一个.写作几乎是微不足道的.然而,与链接相比,我没有看到它有多大优势:
$this.on('click','.trigger a',rowTrigger) .on('click','.actions nav a',rowAction);
但同样,插件并不复杂.这是一个未经测试的草稿:
jQuery.fn.onAny = function(options) { var eventName, eventSpec, eventEntry, selector, i; for (eventName in options) { eventSpec = options[eventName]; if (jQuery.isArray(eventSpec)) { // Your example, where each event name has an array of objects // keyed by selector, where the value is the handler for (i = 0; i < eventSpec.length; ++i) { eventEntry = eventSpec[i]; for (selector in eventEntry) { this.on(eventName, selector, eventEntry[selector]); } } } else { // Assuming just a straight handler here this.on(eventName, eventSpec); } } return this; };