首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在数据属性中添加html元素

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

Stack Overflow用户
提问于 2018-08-20 02:47:08
回答 1查看 1K关注 0票数 1

我想将整个html元素添加到data属性中,这样在单击时我就可以将其设置为localstorage,并可以在下一页上使用它,而不是在下一页上再次执行相同的操作。

这是我所做的..。

检查img_src是否有值

如果为false,则使用字母X和一些样式设置div

如果为true,则使用src和一定的宽度和高度设置img标记

代码语言:javascript
复制
      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

代码语言:javascript
复制
        $(".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的结果是

上图是我的html页面结果

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-20 05:45:48

一种可行的解决方案是使用jQuerys构造函数创建元素,然后使用这些元素设置data-属性来存储它。这个示例可以工作,并且似乎可以做您想要的事情。

代码语言:javascript
复制
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);
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51920810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档