微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用数据选择器写入全局变量

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

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,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>

,

我正在尝试使用 div 和文本而不是链接上的属性进行计数。当然,由于我的新手,它不起作用。我做错了什么?

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。