有人可以解释一下这个 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/