重构jQuery代码块?

时间:2013-10-15 14:43:25

标签: jquery refactoring

我有一段jQuery代码,我不得不一遍又一遍地重复,每次迭代只需要一个小的改动。这是我的一个例子:

  if($('.smm').hasClass('vendor-icon-active')) {
      total = total + 1200;
  } else {
    total = total;
  }

  if($('.repman').hasClass('vendor-icon-active')) {
      total = total + 495;
  } else {
    total = total;
  }

  if($('.blog-management').hasClass('vendor-icon-active')) {
      total = total + 395;
  } else {
    total = total;
  }

  if($('.press-release').hasClass('vendor-icon-active')) {
      total = total + 195;
  } else {
    total = total;
  }

在我的代码中,我有大约30个部分。有没有办法简化这个过程并清理我的代码?

2 个答案:

答案 0 :(得分:5)

您可以使用公共类对元素进行分组,并使用data-*属性来保存与其关联的值。试试这个:

var total = 0;
$('.item').each(function(i, el) {
  var $item = $(el);
  if ($item.hasClass('vendor-icon-active')) {
    total += +$item.data('value');
  }
});
console.log(total);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="smm vendor-icon-active item" data-value="1200">Foo</div>
<div class="repman vendor-icon-active item" data-value="495">Foo</div>
<div class="blog-management vendor-icon-active item" data-value="395">Foo</div>
<div class="press-release vendor-icon-active item" data-value="195">Foo</div>

答案 1 :(得分:2)

这应该可以解决问题......

function updateTotal(className, value) {
    if ($('.' + className).hasClass('vendor-icon-active')) {
        total += value;
    }
}

updateTotal("ssm", 1200);
updateTotal("repman", 495);
updateTotal("blog-management", 395);
updateTotal("press-release", 195);

我刚将主要功能移到了一个功能中。您可以随后添加任意数量的函数调用:)

相关问题