请教,有没有办法给 一个dom 元素 添加 对象格式的 属性 {key:value,key:value} ,setAttribute() 好象没用啊
3条回答 默认 最新
- czDonald 2022-06-15 17:38关注
封装两个方法用于处理对象格式的属性
<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>
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用