[英]How to concise following jquery code snippet
I have the following jQuery code and it works fine but it loads very slowly. 我有以下jQuery代码,它工作正常,但加载速度很慢。 i am not a pro in jQuery so can anyone help me make following code snippet more concise?
我不是jQuery专家,所以有人可以帮助我使以下代码段更简洁吗? I will appreciate this.
我将不胜感激。
jQuery(document).ready(function() {
// colorpicker field
jQuery('.twb_btn_color, .twb_spam_clr, .twb_btn_txt_color, .twb_bg_color, .twb_main_title_color, .twb_sub_title_color')
.each(function(){
var $this = jQuery(this),
id = $this.attr('rel');
$this.farbtastic('#' + id).hide();
jQuery('.twb, .twb-title').click(function() {
jQuery('.twb_btn_color').fadeIn('medium').siblings("div").hide();
});
jQuery('.twb-spam, .twb-spam-title').click(function() {
jQuery('.twb_spam_clr').fadeIn('medium').siblings("div").hide();
});
jQuery('.twb-btn-txt-color, .twb-btn-txt-color-title').click(function() {
jQuery('.twb_btn_txt_color').fadeIn('medium').siblings("div").hide();
});
jQuery('.twb-bg-color, .twb-bg-color-title').click(function() {
jQuery('.twb_bg_color').fadeIn('medium').siblings("div").hide();
});
jQuery('.twb-main-title-color, .twb-main-title-color').click(function() {
jQuery('.twb_main_title_color').fadeIn('medium').siblings("div").hide();
});
jQuery('.twb-sub-title-color, .twb-sub-title-color').click(function() {
jQuery('.twb_sub_title_color').fadeIn('medium').siblings("div").hide();
});
});
});
The typical way of handling this is to give all the elements that you want to perform the same action on the same class name . 处理此问题的典型方法是为要在相同的类名上执行相同操作的所有元素赋值 。
Also, so that you don't have to bind the event to each of them, you can delegate the event on a common parent, in this case we'll use body
: 另外,为了不必将事件绑定到每个事件,可以将事件委托给公共父对象,在这种情况下,我们将使用
body
:
$('body').on('click', '.common-class-name', function () {
$(this).fadeIn('medium').siblings("div").hide();
});
This requires that you give all the elements the same class name. 这要求您为所有元素赋予相同的类名。 You can then reference the one that has been clicked with
$(this)
. 然后,您可以引用
$(this)
单击的那个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.