简体   繁体   中英

How to Add html element in data attribute

I want to add whole html element to data attribute so that on click I can set it to localstorage and can use it on next pages as well instead of doing the same stuff again on next page ...

Here is what I was doing...

Checking if img_src has a value or not
if false than set a div with letter X and some styling
if true set img tag with src and some width and height

      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 on click

        $(".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'));            
        });

But this adding html inside data attirbute results
在此处输入图片说明

This above image is my html page result

One solution that works is using jQuerys constructor to create the elements and then using those elements to set the data- attributes to store it. This example works and seems to do what you want.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM