我试图在数据属性中构建和数组,但是当我试图添加名称和值时,我得到了对象和对象
<div class="wrapper"></div>
$post_url = "http://example.ai";
$post_id = "750";
$(".wrapper").attr("data-history", {
id: $post_id,
url: $post_url
});我首先创建数据属性"history“,但随后它向其添加了对象和对象。在此之后,我需要向下一个事件上的“历史”数组添加另一个名称/值。
发布于 2017-06-17 16:49:59
有两个问题,一个是你不应该有点(.)在class属性和两个类中,您必须将属性添加为JSON (或者使用.data,这取决于您想如何使用该属性)
<div class="wrapper"></div>
$post_url = "http://example.ai";
$post_id = "750";
$(".wrapper").attr("data-history", JSON.strinify({
id: $post_id,
url: $post_url
}));或
$post_url = "http://example.ai";
$post_id = "750";
$(".wrapper").data("history", {
id: $post_id,
url: $post_url
});编辑:
要添加新项,只需获取旧数据并向其添加新数据即可。
$post_url = "http://example.ai";
$post_id = "750";
var data = $(".wrapper").attr("data-history");
if (!data){
data = [];
}
else{
data = JSON.parse(data);
}
data.push({
id: $post_id,
url: $post_url
});
$(".wrapper").attr("data-history", JSON.strinify(data));或
$post_url = "http://example.ai";
$post_id = "750";
var data = $(".wrapper").data("history");
if (!data){
data = [{
id: $post_id,
url: $post_url
}];
}
else{
data.push({
id: $post_id,
url: $post_url
});
}
$(".wrapper").data("history", data);https://stackoverflow.com/questions/44606990
复制相似问题