我在这些HTML

<div data-params="{a: 1, b: '2'}" id="TEST1"></div>
<div data-params='{"a": 1, "b": "2"}' id="TEST2"></div>

Then I use data() method in the jQuery

然后在jQuery中使用data()方法

$('#TEST1').data('params'); //return a string
$('#TEST2').data('params'); //return a object

But TEST1 it's not a return object, but a string, it can only return object TEST2. But I want to get a object by TEST1, How do I do it?

但TEST1不是返回对象,而是字符串,它只能返回对象TEST2。但是我想通过TEST1获得一个对象,我怎么做呢?

=============

= = = = = = = = = = = = =

Finally, I choose to write a function to achieve their own needs

最后,我选择编写一个函数来满足自己的需要

$.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);
};

3 个解决方案

#1


36  

In order to be parsed as an object, the data attribute must be a well formed JSON object.

为了作为对象进行解析,数据属性必须是格式良好的JSON对象。

In your case you just need to quote the object keys (as you do in the second object). Try:

在这种情况下,只需引用对象键(就像在第二个对象中那样)。试一试:

<div data-params='{"a": 1, "b": "2"}' id="TEST1"></div>

For more info see the data method docs, the relevant part is this one (emphasis mine):

更多信息请参阅数据方法文档,相关部分是这个(重点是我的):

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 '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names.

每次尝试将字符串转换为JavaScript值(包括布尔值、数字、对象、数组和空值),否则它就会变成字符串……当数据属性是一个对象(以“{”开头)或数组(以“['开头)时,那么jQuery。parseJSON用于解析字符串;它必须遵循有效的JSON语法,包括引用的属性名。

#2


6  

You can escape the inner quotes:

您可以转义内部引号:

<div data-params="{&quot;a&quot;: 1, &quot;b&quot;: &quot;2&quot;}" id="TEST2"></div>

But there is nothing wrong with your second method:

但是你的第二种方法没有错:

<div data-params='{"a": 1, "b": "2"}' id="TEST2"></div>

I would use that.

我将使用。

#3


0  

Try this one. It's how Uikit parse data attribute json. Hope this will helpful

试试这个。Uikit如何解析数据属性json。希望这将帮助

function str2json(str, notevil) {
  try {
    if (notevil) {
      return JSON.parse(str
                        .replace(/([\$\w]+)\s*:/g, function(_, $1){return '"'+$1+'":';})
                        .replace(/'([^']+)'/g, function(_, $1){return '"'+$1+'"';})
                       );
    } else {
      return (new Function("", "var json = " + str + "; return JSON.parse(JSON.stringify(json));"))();
    }
  } catch(e) { return false; }
}

function options(string) {
  if (typeof string !='string') return string;

  if (string.indexOf(':') != -1 && string.trim().substr(-1) != '}') {
    string = '{'+string+'}';
  }

  var start = (string ? string.indexOf("{") : -1), options = {};

  if (start != -1) {
    try {
      options = str2json(string.substr(start));
    } catch (e) {}
  }

  return options;
}

var paramsData = document.querySelectorAll('[data-params]')[0].dataset.params;

var optionsParsed = options(paramsData);

console.log(optionsParsed);
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>
<body>
  <div data-params="{hello: 'world'}"></div>
</body>
</html>

#1


36  

In order to be parsed as an object, the data attribute must be a well formed JSON object.

为了作为对象进行解析,数据属性必须是格式良好的JSON对象。

In your case you just need to quote the object keys (as you do in the second object). Try:

在这种情况下,只需引用对象键(就像在第二个对象中那样)。试一试:

<div data-params='{"a": 1, "b": "2"}' id="TEST1"></div>

For more info see the data method docs, the relevant part is this one (emphasis mine):

更多信息请参阅数据方法文档,相关部分是这个(重点是我的):

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 '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names.

每次尝试将字符串转换为JavaScript值(包括布尔值、数字、对象、数组和空值),否则它就会变成字符串……当数据属性是一个对象(以“{”开头)或数组(以“['开头)时,那么jQuery。parseJSON用于解析字符串;它必须遵循有效的JSON语法,包括引用的属性名。

#2


6  

You can escape the inner quotes:

您可以转义内部引号:

<div data-params="{&quot;a&quot;: 1, &quot;b&quot;: &quot;2&quot;}" id="TEST2"></div>

But there is nothing wrong with your second method:

但是你的第二种方法没有错:

<div data-params='{"a": 1, "b": "2"}' id="TEST2"></div>

I would use that.

我将使用。

#3


0  

Try this one. It's how Uikit parse data attribute json. Hope this will helpful

试试这个。Uikit如何解析数据属性json。希望这将帮助

function str2json(str, notevil) {
  try {
    if (notevil) {
      return JSON.parse(str
                        .replace(/([\$\w]+)\s*:/g, function(_, $1){return '"'+$1+'":';})
                        .replace(/'([^']+)'/g, function(_, $1){return '"'+$1+'"';})
                       );
    } else {
      return (new Function("", "var json = " + str + "; return JSON.parse(JSON.stringify(json));"))();
    }
  } catch(e) { return false; }
}

function options(string) {
  if (typeof string !='string') return string;

  if (string.indexOf(':') != -1 && string.trim().substr(-1) != '}') {
    string = '{'+string+'}';
  }

  var start = (string ? string.indexOf("{") : -1), options = {};

  if (start != -1) {
    try {
      options = str2json(string.substr(start));
    } catch (e) {}
  }

  return options;
}

var paramsData = document.querySelectorAll('[data-params]')[0].dataset.params;

var optionsParsed = options(paramsData);

console.log(optionsParsed);
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>
<body>
  <div data-params="{hello: 'world'}"></div>
</body>
</html>

标签:

相关文章