我正在尝试这些 HTML
<div data-params="{a: 1, b: '2'}" id="TEST1"></div>
<div data-params='{"a": 1, "b": "2"}' id="TEST2"></div>
然后我在 jQuery 中使用 data() 方法
$('#TEST1').data('params'); //return a string
$('#TEST2').data('params'); //return a object
但是TEST1不是一个返回对象,而是一个字符串,它只能返回对象TEST2。 但是我想通过TEST1得到一个对象,我该怎么做呢?
=============
最后我选择自己写一个函数来实现自己的需求
$.fn.data2 = function(key, value)
{
if (value === undefined)
{
var data = $(this).data(key);
if (typeof(data) === 'string')
{
var _data = data.replace(/^[\s\r\n]*/g, '').replace(/[\s\r\n]*$/g, '');
if (_data.match(/\{.*\}/) || _data.match(/\[.*\]/)) {
try {
_data = (new Function( 'return ' + data ))();
if (typeof(_data) == 'object') {
$(this).data(key, _data);
data = _data;
}
} catch(ex) {}
}
}
return data;
}
return $(this).data(key, value);
};
最佳答案
为了被解析为一个对象,数据属性必须是一个格式良好的 JSON 对象。
在您的情况下,您只需要引用对象键(就像在第二个对象中所做的那样)。尝试:
<div data-params='{"a": 1, "b": "2"}' id="TEST1"></div>
有关详细信息,请参阅 data method docs ,相关部分是这个(强调我的):
Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string... ...When the data attribute is an object (starts with
'{'
) or array (starts with'['
) thenjQuery.parseJSON
is used to parse the string; it must follow valid JSON syntax including quoted property names.
关于javascript - 如何在 jQuery 中将 JSON 格式设置为 HTML5 数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7410348/