1

I have a section of jQuery code that I am having to repeat over and over with only a small change accompanying each iteration. Here is an example of what I have:

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

In my code, I have about 30 of those sections. Is there a way I could simplify that process and clean up my code?

4

2 回答 2

5

You can use a common class to group the elements, and a data-* attribute to hold the value associated with them. Try this:

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>

于 2013-10-15T14:47:22.783 回答
2

This should do the trick...

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

I just moved the main functionality into that one function. You can add as many function calls as you need afterwards :)

于 2013-10-15T14:48:03.147 回答