[英]How to Add html element in data attribute
我想將整個 html 元素添加到 data 屬性,以便在單擊時我可以將其設置為 localstorage 並且可以在下一頁上使用它,而不是在下一頁上再次執行相同的操作...
這是我在做什么...
檢查 img_src 是否有值
如果為假,則設置一個帶有字母 X 和一些樣式的 div
如果為真,則使用 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 頁面結果
一種有效的解決方案是使用 jQuery 構造函數來創建元素,然后使用這些元素來設置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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.