重构:Javascript块

时间:2011-01-10 18:45:56

标签: javascript jquery refactoring

需要一些帮助重构此代码:

$("span[rel=color_content]").ColorPicker({
  onChange: function (hsb, hex, rg) {
    $("span[rel=color_content]").css('background-color', '#' + hex);
  }
});
$("span[rel=color_link]").ColorPicker({
  onChange: function (hsb, hex, rg) {
    $("span[rel=color_link]").css('background-color', '#' + hex);
  }
});
$("span[rel=color_selected]").ColorPicker({
  onChange: function (hsb, hex, rg) {
    $("span[rel=color_selected]").css('background-color', '#' + hex);
  }
});
$("span[rel=color_page]").ColorPicker({
  onChange: function (hsb, hex, rg) {
    $("span[rel=color_page]").css('background-color', '#' + hex);
  }
});
$("span[rel=color_player]").ColorPicker({
  onChange: function (hsb, hex, rg) {
    $("span[rel=color_player]").css('background-color', '#' + hex);
  }
});

唯一改变的是rel属性的内容。

6 个答案:

答案 0 :(得分:6)

// Newlines added for readability
$('span[rel=color_content],
   span[rel=color_link],
   span[rel=color_selected],
   span[rel=color_page],
   span[rel=color_player]').ColorPicker({
       onChange: function(hsb, hex, rg){
           $(this).css('background-color', '#' + hex);
       }
   });

我猜测页面上每个跨度只有一个实例。如果没有,您可以稍微修改它以获得行为相同的方式:

// Newlines added for readability
$('span[rel=color_content],
   span[rel=color_link],
   span[rel=color_selected],
   span[rel=color_page],
   span[rel=color_player]').ColorPicker({
       onChange: function(hsb, hex, rg){
           $('span[rel='+$(this).attr('rel')+']')
               .css('background-color', '#' + hex);
       }
   });

答案 1 :(得分:5)

您可以执行以下操作:

function setColorPicker(css_selector) {
    $(css_selector).ColorPicker({
      onChange: function (hsb, hex, rg) {
         $(css_selector).css('background-color', '#' + hex);
      }
    });
}

答案 2 :(得分:0)

for(i in ['content','link','selected','page','player'])
{
    $("span[rel=color_"+i+"]").ColorPicker({   
    onChange: function (hsb, hex, rg) {$("span[rel=color_"+i+"]").css('background-color', '#' + hex);   } }); 
}

答案 3 :(得分:0)

var arr = [
    'color_content',
    'color_link', 
    'color_selected', 
    'color_page', 
    'color_player'
];

function foo() {
    var i, selector;

    for (i = 0; i < arr.length; i++) {
        selector = 'span[rel=' + arr[i] + ']';

        $(selector).ColorPicker({
            onChange: function (hsb, hex, rg) {
                $(selector).css('background-color', '#' + hex);
            }
        });
    }
}

答案 4 :(得分:0)

如果最终需要维护很长的列表,一种方法是将所有不断变化的信息放在一个易于维护的变量中:

var rels = ['color_content','color_link','color_selected','color_page'];

然后你可以:

// build the selectors according to your patterh
var selectors = $.map( rels, function(e,i){ 
  return 'span[rel=' + rels + ']'; 
}).join(',');

$(selectors).ColorPicker({
  onChange: function(hsb,hex,rg){
    $(this).css('background-color','#'+hex); 
});

答案 5 :(得分:-1)

您可以使用逗号分隔几个CSS选择器:

$("span[rel=color_player], span[rel=color_page]").ColorPicker();