0

我在页面上有可以激活和停用设置的按钮。Id 与它们的前缀相同,例如我有 '#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 等

4

2 回答 2

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

这使用“属性以”选择器结尾

另一种解决方案是更改 HTML 以使用类(“activate”、“deactivate”)和数据属性(“cl”、“rl”)。

于 2013-11-06T09:27:18.350 回答
1

遵循 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. 在代码中为每个前缀构造激活和停用 id 值
  5. 对通用 jQuery 选择器上调用的所有方法使用 jQuery 链接
于 2013-11-06T09:32:59.987 回答