如何重构jquery

时间:2013-11-06 09:25:21

标签: jquery refactoring

我在页面上有一些按钮,可以激活和取消激活设置。 Ids是他们的前缀相同吧例如我有'#rl-activate','#rl-deactivate','#cl-activate','#cl-deactivate'有没有办法重构这段代码所以我不是为页面上的每个按钮执行此操作。

// rl activate
$('#rl-activate').click(function(){
  $('#rl-activate').hide();
  $('#rl-deactivate').show();
  $('#rl').val(50).prop('selected', true);
  $('#rl').prop('disabled', false).trigger('liszt:updated');
  displayCPM();
  newPrice();
  checkSettings();
});

// rl deactivate
$('#rl-deactivate').click(function(){
    $('#rl-deactivate').hide();
    $('#rl-activate').show();
    $('#rl').prop('disabled', true).trigger('liszt:updated');
    $('#rl').val('').trigger('liszt:updated');
    displayCPM();
    newPrice();
    checkSettings();
});

因此,对于下一个,所有改变将是rl到cl到bm等

2 个答案:

答案 0 :(得分:2)

你可以这样做:

$('[id$="-activate"]').click(function(){
  var prefix = this.id.slice(0,2);
  $(this).hide();
  $('#'+prefix+'-deactivate').show();
  $('#'+prefix).val(50).prop('selected', true);
  $('#'+prefix).prop('disabled', false).trigger('liszt:updated');
  displayCPM();
  newPrice();
  checkSettings();
});

$('[id$="-deactivate"]').click(function(){
    var prefix = this.id.slice(0,2);
    $(this).hide();
    $('#'+prefix+'-activate').show();
    $('#'+prefix).prop('disabled', true).trigger('liszt:updated');
    $('#'+prefix).val('').trigger('liszt:updated');
    displayCPM();
    newPrice();
    checkSettings();
});

这使用"attribute ends with" selector

另一种解决方案是将HTML更改为使用类(“激活”,“停用”)和数据属性(“cl”,“rl”)。

答案 1 :(得分:0)

遵循DRY原则,您可以将一些代码分解为一个通用函数,使用jQuery在其自己的代码中大量使用的复制样式,并利用jQuery链接更多:

 function clickCommon(itemToHide, itemToShow) {
    $(itemToHide).hide()
    $(itemToShow).show();
    displayCPM();
    newPrice();
    checkSettings();
 }

 ["#rl", "#cl"].each(function(pref) {

     $(pref + "-activate").click(function() {
         clickCommon(this, pref + "-deactivate");
         $(pref).val(50).prop('selected', true)
            .prop('disabled', false).trigger('liszt:updated');
     });

     $(pref + "-deactivate").click(function() {
         clickCommon(this, pref + "-activate");
         $(pref).prop('disabled', true).trigger('liszt:updated');
             .val('').trigger('liszt:updated');
     });
 });

使用的技术:

  1. 将激活和取消激活点击之间的公共代码计入公共功能
  2. 使用.each()迭代数组中的前缀(jQuery在其实现中内部执行此操作)
  3. 尽可能使用this而不是重新绑定当前元素
  4. 在代码中为每个前缀构建activate和deactivate id值
  5. 对在公共jQuery选择器上调用的所有方法使用jQuery链接
相关问题