【问题标题】:jQuery not return updated data-value [duplicate]jQuery不返回更新的数据值[重复]
【发布时间】:2021-10-18 13:39:22
【问题描述】:
  1. 点击第一个green按钮
  2. 点击查看价格按钮,返回对吗?好的
  3. 点击第二个绿色按钮,然后再次点击查看价格,返回错误!为什么?

$('button.setprice').click(function() {
  var txt = $(this).text();
  $('.price').text(txt).attr('data-price', txt);
});

$('.check').on('click',function(){
  alert($('.price').data('price'))
});
.setprice {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="price"></div>

<button class="setprice">1000</button>
<button class="setprice">2000</button>
<br/>
<button class="check">check price</button>

【问题讨论】:

  • 试试$('.price').attr('data-price')
  • 这能回答你的问题吗? jQuery .data() does not work, but .attr() does
  • attr() 从 DOM 读取,data() 从 jQuery 保存的内存缓存中读取。您需要使用 与 getter 和 setter 相同的方法。你不能混搭。
  • 谢谢大家,现在我明白我的问题是什么了,尊重

标签: javascript jquery


【解决方案1】:

显然,您不能混合使用 data()attr() 函数。这个答案很好地解释了:https://stackoverflow.com/a/8708345/3785618

由于.data() 做了额外的处理,jQuery 将属性评估的结果存储在$.cache - 毕竟,一旦数据属性被评估,每次.data() 调用都重新评估是浪费的 - 特别是因为数据变量可以包含复杂的 JSON 字符串。

虽然,这会起作用:

$('button.setprice').click(function() {
  var txt = $(this).text();
  $('.price').text(txt).data('price', txt);
});

$('.check').on('click',function(){
  alert($('.price').data('price'))
});
.setprice {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="price"></div>

<button class="setprice">1000</button>
<button class="setprice">2000</button>
<br/>
<button class="check">check price</button>

【讨论】:

    猜你喜欢
    • 2013-04-23
    • 1970-01-01
    • 2015-05-25
    • 2022-01-17
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多