【发布时间】:2016-10-23 00:03:23
【问题描述】:
我有一些代码(jQuery):
$(document).on('tap', '#category1-btn', {category : "category1"}, onlineListGen);
$(document).on('tap', '#category2-btn', {category : "category2"}, onlineListGen);
$(document).on('tap', '#category3-btn', {category : "category3"}, onlineListGen);
$(document).on('tap', '#category4-btn', {category : "category4"}, onlineListGen);
$(document).on('tap', '#category5-btn', {category : "category5"}, onlineListGen);
$(document).on('tap', '#category6-btn', {category : "category6"}, onlineListGen);
这似乎违反了 DNRY 规则。更重要的是,类别的数量取决于读取的 JSON 文件,将来我想根据 JSON 文件的内容动态创建 categoryN-btn(s)。因此,有没有办法通过动态生成事件侦听器或以某种方式使用类来完成上述操作?
【问题讨论】:
标签: javascript jquery dynamic event-handling jquery-events