繁体   English   中英

JavaScript关闭-监听类中所有元素的事件

[英]JavaScript Closure - listen event for all elements of a class

是否可以将事件绑定到Closure中类的所有元素? 我知道在jQuery中就像

$('.my_class').click(...)

关闭中是否有类似的内容? 就像是

goog.events.listen('.my_class', ...)

你的意思是下面吗?

参考: http : //closure-library.googlecode.com/git-history/docs/namespace_goog_events.html

var source = new goog.events.EventTarget();
  function handleEvent(e) {
    alert('Type: ' + e.type + '; Target: ' + e.target);
  }
  source.listen('foo', handleEvent);
  // Or: goog.events.listen(source, 'foo', handleEvent);
  ...
  source.dispatchEvent('foo');  // will call handleEvent
  ...
  source.unlisten('foo', handleEvent);
  // Or: goog.events.unlisten(source, 'foo', handleEvent);

正如joeltine已经提到的那样,Google Closure Lib中没有这种本机方法。 您可以使用G库: https//github.com/rhysbrettbowen/G-closure#gon-uid

或创建另一个原型以提供高级侦听方法。 这些碎片可以满足以下基本要素:

yourapp.prototype.listenAll = function(nodes, callbackFunc) {
  for (var i = 0; i < nodes.length; i++) {
    goog.events.listen(nodes[i], type, callbackFunc);
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM