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

时间:2022-12-04 16:05:45

Here's my HTML:

这是我的HTML:

<input type="text" data-setup='{ "method" : "checkbox" }'>

Here's my JavaScript so far:

这是我到目前为止的JavaScript:

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

This then alerts:

然后警告:

ALERT: { "method" : "checkbox" }

But how can I access the JSON "method"? I want to essentially be able to alert the word "checkbox". Any help appreciated.

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

2 个解决方案

#1


5  

JSON.parse would be the simplest way to create a proper object from that JSON:

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
}

Of course this won't work in older browsers, so you'll need to shim it if you want that kind of browser support. Douglas Crockford has a shim here, and or course jQuery has a JSON parsing method if you were already using that utility.

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

#2


2  

You need to use JSON.parse method for this:

您需要使用JSON.parse方法:

var myJSON = JSON.parse( a[i].getAttribute('data-psswrd') );
alert( myJSON );

This is supported in all modern browsers and in IE8+.

所有现代浏览器和IE8 +都支持此功能。

If you need to support older browsers here is little hack. See Browser compatibility section.

如果你需要支持旧版浏览器,那么这就是一个小问题。请参阅浏览器兼容性部

#1


5  

JSON.parse would be the simplest way to create a proper object from that JSON:

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
}

Of course this won't work in older browsers, so you'll need to shim it if you want that kind of browser support. Douglas Crockford has a shim here, and or course jQuery has a JSON parsing method if you were already using that utility.

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

#2


2  

You need to use JSON.parse method for this:

您需要使用JSON.parse方法:

var myJSON = JSON.parse( a[i].getAttribute('data-psswrd') );
alert( myJSON );

This is supported in all modern browsers and in IE8+.

所有现代浏览器和IE8 +都支持此功能。

If you need to support older browsers here is little hack. See Browser compatibility section.

如果你需要支持旧版浏览器,那么这就是一个小问题。请参阅浏览器兼容性部