使用JavaScript从HTML5 data-*属性获取JSON对象

Hal*_*991 6 javascript json

这是我的HTML:

<input type="text" data-setup='{ "method" : "checkbox" }'>
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止的JavaScript:

var a = document.querySelectorAll('[data-setup]')
for (var i=0;i<a.length;i++) {
    alert(a[i].getAttribute('data-setup'));
}
Run Code Online (Sandbox Code Playgroud)

然后警告:

ALERT: { "method" : "checkbox" }
Run Code Online (Sandbox Code Playgroud)

但是我如何访问JSON"方法"?我想基本上能够提醒"复选框"这个词.任何帮助赞赏.

Ada*_*kis 7

JSON.parse是从该JSON创建适当对象的最简单方法:

for (var i=0;i<a.length;i++) {
    var obj = JSON.parse(a[i].getAttribute('data-psswrd'));
    alert(obj.method); //will alert what was in the method property
    console.log(obj); // should log a proper object
}
Run Code Online (Sandbox Code Playgroud)

当然,这在旧版浏览器中不起作用,因此如果您需要这种浏览器支持,则需要对其进行填充.道格拉斯克罗克福德在这里有一个垫片,或者当然jQuery有一个JSON解析方法,如果你已经使用该实用程序.