0

I have a certain number of divs that each have a data-value associated with them. When a user selects the div a class is added to the div. I would like to update the value of an input box depending on which div has a class added. I would also like to decrease the value if the user clicks on the box a second time to remove the class. Here is my jQuery:

$(".vendor-icon").click(function() {
  $(this).toggleClass('vendor-icon-active');

  var total = 0;
  var item = $(this);

  if ($(item).hasClass('vendor-icon-active')) {
    total = total + $(item).data('value');
  }

  if (!$(item).hasClass('vendor-icon-active')) {
    total = total - $(item).data('value');
  }

});

Here is an example of how the divs are set up:

<div class="vendor-icon website-management" data-value="300"></div>
<div class="vendor-icon make-an-offer" data-value="200"></div>
<div class="vendor-icon email-marketing" data-value="100"></div>

If the first and second div are selected, then the value of the input should be 500. If the second of third div is selected, then the value of the input should be 300.

Right now, if the user selects the first div, the value is 300. If they then select the second div, the value changes to 200 and not 500. Also, if the user clicks on the first div the value will show 300 but if they click the div again, the value will change to -300 instead of 0.

4

1 回答 1

1

你的total变量是一个局部变量,所以每次调用你的函数时它都会被重置(并且不能在函数之外访问)。所以要么将它移动到周围的范围,以便它在调用之间保留它的值:

var total = 0;
$(".vendor-icon").click(function() {
  var item = $(this).toggleClass('vendor-icon-active');    
  if (item.hasClass('vendor-icon-active')) {
    total += item.data('value');
  } else {
    total -= item.data('value');
  }
});

请注意,您可以使用if/else结构,无需对操作符重复相同的.hasClass()测试!。或者您可以?:改用:

total += item.hasClass('vendor-icon-active') ? item.data('value') : -item.data('value');

请注意,无论哪种方式,您都在创建一个item已经是 jQuery 对象的变量,所以当您使用它时,您只需说item.hasClass(...),您不需要$()再次包装它。

或者,实现这一点的另一种方法是遍历所有选定的 div 并在每次点击时添加它们:

$(".vendor-icon").click(function() {
  $(this).toggleClass('vendor-icon-active');

  var total = 0;    
  $(".vendor-icon-active").each(function() {
     total += $(this).data('value');
  });    
  // do something with total
});
于 2013-10-15T20:11:21.967 回答