gpt4 book ai didi

javascript - 在追加之前将数据存储在元素上

转载 作者:行者123 更新时间:2023-12-02 14:31:55 26 4
gpt4 key购买 nike

我想使用 jquery data() 在 html 元素上存储 JSON。然而我的元素实际上是一个 html 字符串,并且还没有像这样在 DOM 中。

$(".test").each(function() {
el += "<span>"+ 25 +"</span>";
});

$("body").append(el);

我已经尝试过这个(在每个函数中)

el += $("<span>"+ 25 +"</span>").data("test", {"name":"john"});

但是当我附加el时,我会附加[object][object]

如何将数据与元素相关联并能够在附加后检索它?

fiddle :https://jsfiddle.net/6mhgwtk1/1/

最佳答案

你做对了,但它是一个对象。当您打印或警告对象时,它将始终显示为[Object]。不是打印对象而是打印它的属性,如下所示:el.data("test").name.

参见:https://jsfiddle.net/6mhgwtk1/

<小时/>根据您的示例代码,我已经用工作代码更新了您的 fiddle 。请参阅评论的解释.. https://jsfiddle.net/6mhgwtk1/3/

var el;
$("div").each(function() {
// el is not a string here, (it's a jQuery object) so you can't concatentate it using +=
// instead you will have to append each one to the body separately
el = $("<span>"+ 25 +"</span>").data("test", {"name":"john"});
$("body").append(el);
});


$("body").find("span").each(function(){
var data = $(this).data("test");
console.log(data);
});

关于javascript - 在追加之前将数据存储在元素上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37739392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com