如何将javascript对象存储为数据属性并进行编辑
我正在生成json并将其存储为数据属性。 例如
data-categories="{"2":{"categoryId":"2","name":"how to's"},"5":{"categoryId":"5","name":"about us"},"6":{"categoryId":"6","name":"proucts"}}"
当我稍后尝试编辑并保存新的json时,它没有被保存,旧的数据仍然存在。
例如
//获取现有类别var currentCategories = $(’li#’+ $(this).data(’backgroundid’)+’。categoryTags .addCategory’)。data(’categories’); //获取名称,如果是从at到link
var newCategory = {‘tagid’:$(this).data(’categoryid’),’name’:$(this).data(’categoryname’)} currentCategories = [$(this).data(’backgroundid’) ] .push(newCategory); //当我在这里记录对象时,它很好,包含旧类别和新类别
//save the new string back to the data attribute of li elsewhere on page $('li#'+ $(this).data('pageid')+' .categoryNames .addCategory').data('categories',currentCategories);
但是圆顶中的数据仍然是相同的,当我稍后尝试引用它时
我认为你可能会被你在元素的实际DOM属性中看到的东西误导(在开发人员工具中看到)。
创建新的jQuery对象时,在受影响的节点上找到的任何HTML5 data- *属性(如果有)都会自动传输到jQuery实例的内部.data()存储。 所以“数据类别” 在创建时被jQuery扫描到一个对象中。
当使用jQuery的.data()
方法时,它不会尝试更新底层DOM,因为它使用了两倍的开销(操纵DOM比在纯JavaScript中工作慢)。
换句话说, jQuery.data与使用HTML5 data-
属性不同。
如果你在为其分配修改后的类别哈希后调用jQuery(el).data(“categories”),它很可能会返回你期望的内容。 🙂