使用数据选择器写入全局变量

Write to global variable with data selector

我想使用数据选择器写入全局变量。这可能吗? (请温柔一点,我的经验很浅:)

var one = 0;
var two = 0;
var three = 0;

$("a[data-typ]").click(function() {

  if ($(this).hasClass('active')) {

    $(this).removeClass('active');
    $(this).data("typ").toString--;

  } else {

    $(this).addClass('active');
    $(this).data("typ").toString++;

  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-typ='one'>One</a>
<a data-typ='two'>Two</a>
<a data-typ='three'>Three</a>

你是这个意思吗?

var one = 0;
var two = 0;
var three = 0;

$("a[data-typ]").click(function() {
  const typ = $(this).data("typ")
  if ($(this).is('.active')) {
    window[typ]--
  } else {
    window[typ]++
  }
  console.log(one,two,three)
  $(this).toggleClass("active");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-typ='one'>One</a>
<a data-typ='two'>Two</a>
<a data-typ='three'>Three</a>

如果您需要拆分一个属性中的多个数据类型:

var one = 0;
var two = 0;
var three = 0;

$("a[data-typ]").click(function() {
  const types = $(this).data("typ").split(" "); // split on space.
  const active = $(this).is('.active');
  types.forEach(typ => { 
    if (active) {
      window[typ]--
    } else {
      window[typ]++
    }
  })
  console.log(one, two, three)
  $(this).toggleClass("active");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-typ='one three'>One and three</a>
<a data-typ='two'>Two</a>