通过属性传递属性/对象。Javascript

I a*_*m L 5 html javascript attributes object polymer

有没有办法通过属性传递数组或对象?喜欢:

<div id="myelem" myattr="{ title: 'hello', author: 'mike'}, { title: 'world', author: 'hellen'}, {...}"/>
Run Code Online (Sandbox Code Playgroud)

我只是使用 javascript 尝试过这个,但只返回了第一个对象,我想要这样的东西:

for(let i=0; i<this.myattr.length; i++){
  console.log(this.myattr.title);
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?谢谢

Cod*_*rPi 5

您必须*使用JSON.parse()并且您的字符串必须采用有效的 JSON 格式。

var element = document.getElementById('myelem')
var attributeContent = element.getAttribute('data-myattr')
var object = JSON.parse(attributeContent)
Run Code Online (Sandbox Code Playgroud)
<div id="myelem" data-myattr='[{ "title": "hello", "author": "mike" }, { "title": "world", "author": "hellen" }]' />
Run Code Online (Sandbox Code Playgroud)

*您也可以不需要var object = eval(attributeContent)JSON 字符串。但是看看“为什么使用 JavaScript eval 函数是个坏主意?


最后,我想建议使用<script>标签而不是属性来通过您的 HTML 代码传递 JavaScript 对象:

<script>
    var myStuff = [{ title: 'hello', author: 'mike' }, { title: 'world', author: 'hellen' }, {}];
</script>
Run Code Online (Sandbox Code Playgroud)

然后您将能够myStuff在您的 JavaScript 代码中访问