[英]Can we assign an object to a html element in plain JavaScript without jQuery
I want to store an object as an attribute of an HTML element! 我想将对象存储为HTML元素的属性! Let's suppose I'm having a div element and when I click the div element I want to get the values of the object from the div element so that I can use it in the click function.
假设我有一个div元素,当我单击div元素时,我想从div元素获取对象的值,以便可以在click函数中使用它。
I've seen people doing it in jquery but I want it in pure javascript since I'm writing a typescript code and I don't want jQuery 我见过有人在jquery中这样做,但是我想用纯JavaScript编写,因为我正在编写打字稿代码,而且我不想要jQuery
ex:
var myNewObject={
"first_name": "Sam",
"last_name": "carter"
}
var div=document.getElementByID("myID");
div.setAttribute("myobject",myNewObject);
<div onclick="somefunc()>
</div>
function somefunc()
{
console.log(document.getAttribute("myobject").first_name);
}
Expected output: Sam 预期输出:Sam
Actual output: Error 实际输出:错误
You can store any Javascript objects on an HTMLElement
directly: 您可以将任何Javascript对象直接存储在
HTMLElement
:
const div = document.createElement('div');
div.myobject = { hello: 'world' };
Only strings can be stored in attributes, and the string representation of an object is [object Object]
. 属性中只能存储字符串,并且对象的字符串表示形式为
[object Object]
。 If you must use attributes you can serialize the object and store it and then deserialize it when you retrieve it again: 如果必须使用属性,则可以序列化对象并存储它,然后在再次检索它时反序列化它:
const obj = { hello: 'world' }; const a = document.querySelector('#a'); a.setAttribute('myobject', JSON.stringify(obj)); const obj2 = JSON.parse(a.getAttribute('myobject')); console.log(obj2.hello);
<div id="a">Hello</div>
Storing state in DOM is generally considered bad practice in any case. 在任何情况下,将状态存储在DOM中通常被认为是不好的做法。
Here is another approach. 这是另一种方法。 This is a good time to learn about Map which is similar to an object but the key can be any type, not just strings.
这是学习与对象相似的Map的好时机,但是键可以是任何类型,而不仅仅是字符串。 You can use the element as a key and the object as the value.
您可以将元素用作键,将对象用作值。
const elementMap = new Map();
const myElement = document.querySelector("#myElement");
const myObject = {x: 0, y: 0, z: 0};
elementMap.set(myElement, myObject);
...
//later we can access the object by that element
const myElement = document.querySelector("#myElement");
const myObject = elementMap.get(myElement);
Here are two big advantages of this approach. 这是此方法的两个主要优点。
1. No need to worry about name collisions with properties of the HTML element, or possibly other code modifying the element's properties. 1.无需担心与HTML元素的属性发生名称冲突,也不必担心修改该元素的属性的其他代码。
2. The object is the same object you originally had, which can be important if you care about the reference which is not preserved if you use the JSON string solution. 2.该对象与您最初拥有的对象相同,如果您关心使用JSON字符串解决方案时不保留的引用,则这很重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.