且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何将javascript对象存储为数据属性并进行编辑

更新时间:2023-01-12 11:03:05

我认为你可能会被你在元素的实际DOM属性中看到的东西误导(在开发者工具中看到) 。

I think you may be being mislead by what you're seeing in the element's actual DOM attribute (as viewed in the developer tools).

创建新的jQuery对象时,受影响节点上的任何HTML5 data- *属性(如果有)都会自动传输到jQuery实例的内部.data()存储。因此,数据类别正在被jQuery 创建 时扫描到对象中。

When creating a new jQuery object, any HTML5 data-* attributes found on the affected nodes, if any, are automatically transferred to the jQuery instance's internal .data() storage. So "data-categories" is being swept into an object by jQuery upon creation.

当使用jQuery的 .data()方法时,它不会尝试更新底层DOM,因为它使用两倍的开销(操纵DOM比在纯JavaScript中工作慢)。

When jQuery's .data() method is used, it won't attempt to update the underlying DOM, since that'd use twice as much overhead (manipulating the DOM is slower than working in pure JavaScript).

换句话说, jQuery.data 与使用HTML5 数据 - 属性相同。

In other words, jQuery.data is not the same as using HTML5 data- attributes.

如果你是在为jQuery(el).data(categories)分配修改后的类别哈希之后调用它,它很可能会返回你期望的内容。 :)

If you were to call jQuery(el).data("categories") after assigning it the modified category hash, it'd most likely return what you expect. :)