gpt4 book ai didi

javascript - 如何在数据属性中添加 html 元素

转载 作者:行者123 更新时间:2023-11-30 20:15:54 25 4
gpt4 key购买 nike

我想将整个 html 元素添加到数据属性中,以便在单击时我可以将其设置为 localstorage 并且也可以在下一页上使用它,而不是在下一页上再次做同样的事情......

这是我正在做的...

检查 img_src 是否有值
如果为 false,则设置一个带有字母 X 和一些样式的 div
如果为 true,则使用 src 和一些宽度和高度设置 img 标签

      var img_src="userpic.png"; //this value comes from db
if(img_src=="" || img_src==null){
var po_img = '<div class="class-groupPic bg-1">X</div>';
}
else{
var po_img = '<img src="'+element.student.photo+'" width="34" height="34"/>';
}

<div class="col" data-img="'+po_img+'" data-religion="Hindu" data-category="OBC"></div>

点击时的 Jquery

        $(".col").on('click',function(){
window.localStorage.setItem('img',$(this).data('img'));
window.localStorage.setItem('religion',$(this).data('religion'));
window.localStorage.setItem('category',$(this).data('category'));
});

但是在数据属性中添加 html 结果
enter image description here

上面这张图片是我的html页面结果

最佳答案

一个有效的解决方案是使用 jQuerys 构造函数创建元素,然后使用这些元素设置 data- 属性来存储它。这个例子有效,似乎可以做你想做的事。

var img_src = "userpic.png"; //this value comes from db
var element = {
student: {
photo: "myImage.com"
}
}; // for this example only

var $po_img;
if (img_src == "" || img_src == null) {
$po_img = $('<div>', { class: "class-groupPic bg-1"});
$po_img.text("X");
} else {
$po_img = $('<img/>', {src: element.student.photo, width: 34, height: 34});
}

var $myDiv = $('<div/>', { id: "myDiv", class: "col"});
$myDiv.text("I am the div");
$myDiv.attr("data-img", $po_img[0].outerHTML);
$myDiv.attr("data-religion", "Hindu");
$myDiv.attr("data-category", "OBC");

// add the div to the DOM
document.write($myDiv[0].outerHTML);

// Retrieve the img HTML from the div's data attribute
var theImage = $("#myDiv").attr("data-img");
console.log(theImage);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 如何在数据属性中添加 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51920810/

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