【问题标题】:How to concise following jquery code snippet如何简洁以下jquery代码片段
【发布时间】:2014-12-23 09:33:15
【问题描述】:

我有以下 jQuery 代码,它运行良好,但加载速度很慢。我不是 jQuery 的专业人士,所以任何人都可以帮助我使以下代码 sn-p 更简洁吗?我会很感激的。

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();
            });
    });
});

【问题讨论】:

  • 您不需要在每个块中绑定事件处理程序。将它们移动到 document ready 处理程序
  • 你能解释一下怎么做吗?

标签: javascript php jquery wordpress plugins


【解决方案1】:

处理此问题的典型方法是为您希望对相同的类名执行相同操作的所有元素提供。

此外,为了不必将事件绑定到每个事件,您可以将事件委托给一个共同的父级,在这种情况下我们将使用body

$('body').on('click', '.common-class-name', function () {
   $(this).fadeIn('medium').siblings("div").hide();
});

这要求您为所有元素赋予相同的类名。然后您可以使用$(this) 引用已单击的那个。

【讨论】:

  • 感谢您的帮助。
  • 不幸的是,它没有解决我的问题。因为点击它应该触发一个单独的 div 中的函数。不在同一个 div 中,所以 $(this) 在这里不起作用。 HTML代码结构如下:<input class="common_class-name" /> <div class="div that loads when clicked on common class name"></div>
  • @absikandar 如果它们总是相对的,那么您也许可以使用.closest().next() 之类的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 2019-03-10
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多