请教,有没有办法给 一个dom 元素 添加 对象格式的 属性 {key:value,key:value} ,setAttribute() 好象没用啊
封装两个方法用于处理对象格式的属性
<div id="app"></div>
<script>
function setAttribute(selectors, name, value) {
const newValue = JSON.stringify(value);
document.querySelector(selectors).setAttribute(name, newValue);
}
function getAttribute(selectors, name) {
const value = document.querySelector(selectors).getAttribute(name);
return JSON.parse(value);
}
setAttribute('#app', 'name', { a: 1, b: 2 })
const value = getAttribute('#app', 'name')
console.log(value) // {a: 1, b: 2}
</script>
<div id="demo">213</div>
<script type="text/javascript">
document.getElementById('demo').setAttribute('name',`{key:1,key:2}`)
</script>
字符串是可以的, 然后取值时 JSON.parse