重构 jQuery 代码块



我有一段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 个这样的部分。有没有办法简化该过程并清理我的代码?

可以使用公共类对元素进行分组,并使用 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>

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

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

我只是将主要功能移到了一个函数中。 之后,您可以根据需要添加任意数量的函数调用:)

最新更新