javascript - jQuery .removeData() 没有按预期工作

标签 javascript jquery html

有人可以解释一下这个 jQuery 行为吗?我有 data-hello 属性,当我调用 .removeData('hello') 我希望它不会影响任何东西,因为该属性仍然存在,下一个 .data() 调用应该简单地从 data-hello 属性中重新检索值。为什么它没有在下面的代码中这样做。

console.log($('.outer').data())

//removing jquery data (should only remove jquery cache?)
$('.outer').removeData('hello')

// attribute is still there but .data() call not getting it
console.log($('.outer').data())
console.log($('.outer').attr('data-hello'))
<div class="outer" data-hello=1 >hello</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

描述预期行为的文档 https://api.jquery.com/removeData/

Note that .removeData() will only remove data from jQuery's internal .data() cache, and any corresponding data- attributes on the element will not be removed. A later call to data() will therefore re-retrieve the value from the data- attribute.

最佳答案

因为 jQuery 的 data() 返回内部缓存。由于您已删除 key hello,因此 data() 不应再次看到 hello

如果你再次读取键hello,然后它进入数据内部缓存,然后data()可以再次看到它。

请看下面的演示:

console.log('init data(): ' + JSON.stringify($('.outer').data()))

//removing jquery data key from jquery data cache
$('.outer').removeData('hello')

// attribute is still there, .data() call not getting it
console.log('removed data(): ' + JSON.stringify($('.outer').data()))

// read the key again, it comes from the html attribute to the cache
console.log('call data(hello): ' + JSON.stringify($('.outer').data('hello')))

// then the data() can see the key
console.log('then data(): ' + JSON.stringify($('.outer').data()))

console.log($('.outer').attr('data-hello'))
<div class="outer" data-hello=1 >hello</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

关于javascript - jQuery .removeData() 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54112816/

相关文章:

javascript - 预选第二个 <select> 的链接选择

html - 在 iframe srcdoc 值中转义引号

html - 两张并排的 table - 将一张 table 向右对齐

javascript - paypal支付页面价格计算

javascript - 垄断选择随机卡和流行阵列

php - Jquery重定向到另一个页面

php - JavaScript 传递变量并从 PHP 页面检索输出

javascript - 在已安装的情况下仅在 vue 中重新加载页面一次

javascript - setTimeout 未在 android webkit 中调用

javascript - 使用 Joi,如何将 .or 用于递归对象