【问题标题】:Write to global variable with data selector使用数据选择器写入全局变量
【发布时间】:2021-03-30 02:35:01
【问题描述】:

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

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>

【问题讨论】:

    标签: jquery jquery-selectors global-variables increment decrement


    【解决方案1】:

    你是这个意思吗?

    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>

    【讨论】:

    • 哇。谢谢!是否可以一键添加到两个变量。像 一加三 ?
    • 原则上是的。然后你需要拆分类型和循环
    • 好的。我只是对你的意思有一点了解(实际上没有>新手;)如果对你没有问题,你会展示它吗?
    • 所以从给出用例开始。这样做的目的是什么?
    • 我更新了我的答案以处理属性中的多个类型
    【解决方案2】:

    我正在尝试使用 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, two, 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> 
      

    【讨论】:

      猜你喜欢
      • 2012-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 2013-03-23
      • 2016-04-24
      • 1970-01-01
      相关资源
      最近更新 更多