jQuery和原生js在数据属性上不一致

jQuery和原生js在数据属性上不一致,jquery,Jquery,jQuery属性集与本机js设置的属性不一致,显然它们是同时存在的。谁能告诉我发生了什么事 $(document).ready(function() { document.getElementById('attributed').setAttribute('data-foo','mydiv2'); $('#attributed').data('foo','mydiv4'); // jQuery thinks it's mydiv 4 alert($(

jQuery属性集与本机js设置的属性不一致,显然它们是同时存在的。谁能告诉我发生了什么事

$(document).ready(function() {
    document.getElementById('attributed').setAttribute('data-foo','mydiv2'); 

    $('#attributed').data('foo','mydiv4');   

    // jQuery thinks it's mydiv 4 
    alert($('#attributed').data('foo'));     

    // native thinks it's mydiv 2! 
    alert(document.getElementById('attributed').getAttribute('data-foo'));
});
jQuery的
.data()
仅在其自身的
.data()
数据结构中没有为该元素和该键设置任何内容时,才从DOM元素读取实际属性。因此,一旦使用jQuery的
.data()
为该键设置了一个值,它的值将与元素上的实际HTML属性的值不同


这样做有两个原因。如果javascript对象与DOM对象(作为属性)直接关联,则早期浏览器存在内存泄漏问题。而且,纯属性只能是字符串。jQuery的
.data()
没有这两个问题。

IIRC jQuery将数据集保存在内存中的普通JS对象中,并且实际上不会将其写入DOM.Yup-就是这样