【问题标题】:Why jQuery.data() method does not update my data attribute? [duplicate]为什么 jQuery.data() 方法不更新我的数据属性? [复制]
【发布时间】:2014-12-26 12:53:38
【问题描述】:

有一个这样的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 html custom-data-attribute


    【解决方案1】:

    当您使用 jQuery .data() 方法存储数据时,它会在内部存储数据并且不会更新HTML5 data- attribute

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

    您可能会因为 .data() 方法的 getter 版本的工作方式而感到困惑。当你调用 $elem.data('someAttr') 时:

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

    例子:

    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 中找出确切的行为,但它是一个非常糟糕的代码,所以相当经验性地尝试了它;)

    供参考涉及此问题的其他一些问题:

    【讨论】:

    • 不知道为什么这被否决了,甚至听起来像重复,但对于其他一些搜索原因仍然有用
    猜你喜欢
    • 2020-07-20
    • 2011-12-26
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2020-11-26
    • 2015-12-15
    相关资源
    最近更新 更多