jquery - 为什么 jQuery.data() 方法不更新我的数据属性?

标签 jquery html custom-data-attribute

有一个像这样的html:

<div id="mydiv" data-hoo-foo="bar"></div>

我正在尝试以下操作:

var $mydiv = $('#mydiv');
$mydiv.data('hoo-foo');      // returns 'bar'
$mydiv.data('hoo-foo', 'asdf');
$mydiv.data('hoo-foo');      // returns 'asdf'
$mydiv.attr('data-hoo-foo'); // returns 'bar'

为什么会这样呢?

最佳答案

当您使用 jQuery 存储数据时 .data()内部存储数据并且更新HTML5 data- attribute

它的作用是,当您第一次调用 .data() 方法时,它会从 data- 属性初始化内部缓存中的值。

您可能会对 .data() 方法的 getter 版本的工作原理感到困惑。当您调用 $elem.data('someAttr') 时:

  1. 在 $.cache 中查找驼峰式大小写键(例如 someAttr)。如果找到,则返回该值。
  2. Changes将驼峰式大小写键输入破折号分隔的版本(例如 some-attr)并再次尝试。如果找到,则返回该值。如前所述,该值可能源自 HTML5 data- 属性。

示例:

var $mydiv = $('#mydiv');
$mydiv.data('hoo-foo');        // 'bar' - initialized from the data attribute
$mydiv.data('hooFoo');         // 'bar' - initialized from the data attribute
$mydiv.attr('data-hoo-foo');   // 'bar' - directly from the data attribute

$mydiv.data('hoo-foo', 'asdf');
$mydiv.data('hooFoo');         // 'asdf' - from the stored data by 'hoo-foo' key
$mydiv.data('hoo-foo');        // 'asdf' - from the stored data by 'hoo-foo' key
$mydiv.attr('data-hoo-foo');   // 'bar' - the data attribute remains unchanged

$mydiv.data('hooFoo', 'blah');
$mydiv.data('hooFoo');         // 'blah' - key 'hooFoo' exists
$mydiv.data('hoo-foo');        // 'asdf' - key 'hoo-foo' exists
$mydiv.attr('data-hoo-foo');   // 'bar' - still unchanged

$mydiv.data('hoo-foo', 'ugh'); // this will override the 'hooFoo' key too
$mydiv.data('hooFoo');         // 'ugh'
$mydiv.data('hoo-foo');        // 'ugh'
$mydiv.attr('data-hoo-foo');   // 'bar' - still unchanged

$mydiv.removeData('hoo-foo');  // removes both 'hooFoo' and 'hoo-foo' keys
$mydiv.data('hooFoo');         // 'bar' - key 'hooFoo' adn 'hoo-foo' undefined
                               // initializing as 'hoo-foo' from data- attribute
$mydiv.data('hoo-foo');        // 'bar' - key 'hoo-foo' exists
$mydiv.attr('data-hoo-foo');   // 'bar' - still unchanged

我很难弄清楚这个问题,但没能找到完整的答案。这就是我将其发布在这里的原因。如果有什么不准确的地方请纠正我。我试图从 the code 中找出确切的行为,但这是一个非常多的代码,所以根据经验尝试一下;)

供引用涉及此问题的其他一些问题:

关于jquery - 为什么 jQuery.data() 方法不更新我的数据属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27657433/

相关文章:

html - 在 Bootstrap 面板标题中使用带有 div 和 span 的省略号

html - css 将图像对齐到标题和段落的中心

css - CSS 数据属性在移动浏览器上可用吗?

javascript - 如何使用JQuery获取数据属性?

javascript - 循环数组以设置 value = vals[0] ||值[1] || jQuery 中的 vals[2]

javascript - 将 div 及其子元素转换为模态/弹出窗口?

javascript - 将对象存储在 div 中并通过 Jquery 检索

jquery - 获取第二个子元素

html - HTML 属性的长度有限制吗?

javascript - 获取窗口(浏览器)的最大高度,无论浏览器是否最大化