[英]more efficient way of using .on() in jquery
I'm currently building an app
that has makes use of the .on()
in jQuery
.我目前正在构建一个使用
jQuery
中的.on()
的app
。
What I've noticed is, i am making alot of use of the .on()
method.我注意到的是,我正在大量使用
.on()
方法。 so much so, that it feels like my code is starting to become very messy.如此之多,以至于感觉我的代码开始变得非常混乱。
$(document).on('click','.close-comments',function(){
shrinkComments();
});
// end function
$(document).on('click','.reload',function(){
// perform reload
});
// end function
$(document).on('click','.write-comment',function(){
});
// end function
$(document).on('click','#load-more',function(){
});
// end function
What I'm wondering is... is there a more efficient way of using the .on()
method to handle a variety of different clicks on things that may be happening throughout the page?我想知道的是......是否有更有效的方法来使用
.on()
方法来处理整个页面中可能发生的各种不同的点击?
Alot of the content is loaded via ajax
, so the content will vary, but im just looking for a more elegant way of using this method so my code is much more leaner and more efficient很多内容是通过
ajax
加载的,所以内容会有所不同,但我只是在寻找一种更优雅的方式来使用这种方法,所以我的代码更精简、更高效
thanks in advance提前致谢
var clickHandlers = {
'.close-comments' : function() {
shrinkComments();
},
'.reload': function() {
// perform reload
},
'.write-comment': function() {
},
'#load-more': function() {
}
};
for (var selector in clickHandlers) {
$(document).on('click', selector, clickHandlers[selector]);
}
If you want to handle events other than click
, you could add another layer to your handler
object and another layer in the for loop.如果您想处理
click
以外的事件,您可以向handler
对象添加另一个层,并在 for 循环中添加另一个层。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.