我如何将javascript对象存储为数据属性并进行编辑
我正在生成json并将其存储为数据属性。
例如
I am generating json and storing it as a data attribute. e.g.
data-categories="{"2":{"categoryId":"2","name":"how to's"},"5":{"categoryId":"5","name":"about us"},"6":{"categoryId":"6","name":"proucts"}}"
当我稍后尝试编辑并保存新的json时,它没有被保存,旧的数据仍然存在。
When I later try to edit and save the new json it is not being saved and the old dat still exists.
例如
//获取现有类别
var currentCategories = $('li#'+ $(this).data('backgroundid')+'。categoryTags .addCategory ')的数据(' 类别);
//获取名称,如果是从at到链接
var newCategory = {'tagid':$(this).data('categoryid'),'name':$(this ).data('categoryname')}
currentCategories = [$(this).data('backgroundid')]。push(newCategory);
//当我在这里记录对象时它很好包含旧类别和新类别
//get the existing categories
var currentCategories = $('li#'+ $(this).data('backgroundid')+' .categoryTags .addCategory').data('categories');
//get then name and if from the at to link
var newCategory = {'tagid': $(this).data('categoryid'), 'name': $(this).data('categoryname')}
currentCategories=[$(this).data('backgroundid')].push(newCategory);
//when I log the object here it is fine contains the old categories and the new category
//save the new string back to the data attribute of li elsewhere on page
$('li#'+ $(this).data('pageid')+' .categoryNames .addCategory').data('categories',currentCategories);
但是圆顶中的数据仍然是相同的,当我稍后尝试引用它时
But the the data is still the same in the dome and when I try to reference it later
我认为你可能会被你在元素的实际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. :)