重构:Javascript块

Shp*_*ord 0 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);
  }
});
Run Code Online (Sandbox Code Playgroud)

每个之间唯一变化的是rel属性的内容.

Jus*_*ner 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);
       }
   });
Run Code Online (Sandbox Code Playgroud)

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

// 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);
       }
   });
Run Code Online (Sandbox Code Playgroud)


Tia*_*tos 5

你可以这样做:

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