元素数据更改时,jQuery的data()属性不会更新 [英] jQuery's data() attribute does not update when element data changes

查看:96
本文介绍了元素数据更改时,jQuery的data()属性不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jQuery的data() api检索元素的所有数据属性.但是此api的缓存性质确实令人讨厌.有时我需要更改javascript中某个元素的某些数据属性,但data() api总是返回每个数据属性的初始值.因此,我必须使用attr()来访问元素的每个数据属性以获取其最新值.有什么方法可以克服此缓存问题,并使data()每次调用它时始终返回最新值?

I wanna use jQuery's data() api to retrieve all the data attribute of an element. But the cache nature of this api is really annoying. Sometimes I need to change some data atribute of an element in javascript but the data() api always return the initial value of each data attribute. So I have to use the attr() to access each data attribute of an element to get its up-to-date value. Is there any way to overcome this cache thing and make data() always return the latest value every time I call it?

推荐答案

简短的答案是:请勿使用jQuery .data()动态设置数据属性,除非您可以保证始终设置数据属性由jQuery .

以下任何一种解决方案都可以使用:

Either solution below will work:

  • 改为使用普通JS .getAttribute()
  • 改为使用jQuery .attr()
  • Use vanilla JS .getAttribute() instead
  • Use jQuery .attr() instead

这是jQuery文档中的相关部分(我没有认为确实突出了这可能会使jQuery用户感到惊讶):

Here's the relevant part from the jQuery documentation (which I don't think really highlights how much this might surprise jQuery users):

第一次访问data属性时将提取data-属性,然后不再对其进行访问或对其进行突变(然后将所有数据值存储在jQuery内部).

关于为什么使用jQuery设置属性的原因:许多客户端模板语言都构建DOM,包括数据属性.

Regarding why you might not use jQuery to set attributes: many client side templating languages build DOM, including data attributes.

给出动态生成的HTML(如DevTools中所示:

Given the dynamically built HTML (as shown in DevTools:

<form data-test="300" ...

DOM API告诉了事实:

DOM API tells the truth:

 document.querySelector('form').getAttribute('data-test');

jQuery 返回过期的先前值(在这种情况下为19000):

JQuery returns an out-of-date previous value (in this case, 19000):

 $('form').data('test');

jQuery attr返回当前值:

jQuery attr returns the current value:

 $('form').attr('data-amount');

Vanilla JS getAttribute()返回当前值:

Vanilla JS getAttribute() returns the current value:

 document.querySelector('form').getAttribute('data-amount');

这篇关于元素数据更改时,jQuery的data()属性不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆