【问题标题】:How to get the json from a data attribute using only .attr() (or equivalent)如何仅使用 .attr() (或等效项)从数据属性中获取 json
【发布时间】:2017-05-09 15:34:30
【问题描述】:

我觉得我被困在最简单的事情上,但我似乎找不到解决问题的方法。

我有一个 json 数组,我想通过这样的 div 上的数据属性将它传递给我的 javascript:

<div id="scope" data-json='["apple","pear"]'></div>

我的问题是我只能使用除 .data('json') 之外的任何东西来获得该值。

这是我要找的东西:https://jsfiddle.net/Wurielle/p17d71m0/1/

您可以在控制台中看到使用 .data() 进行日志记录会返回一个 json 数组(这正是我需要的),但使用 .attr() 进行日志记录只会返回纯文本。 不幸的是,由于多种原因,我不能使用 .data()。

我考虑过使用 JSON.stringify 和 JSON.parse,但我无法获得与 .data() 选项相同的结果。

除了 .data() 之外,有没有办法从数据属性中获取 json?

【问题讨论】:

  • 你回答了...你需要使用 attr("data-json") 和 JSON.parse()... 看起来很奇怪你不能使用 data()
  • 使用 JSON.parse? console.log(JSON.parse($('#scope').attr('data-json')));
  • 使用dataSet...?
  • Mathijs Rutgers 感谢您的回答,它确实有效!我之前确实尝试过,但我用我的值记录文本,这就是为什么我认为它不能正常工作。傻我哈哈!不管怎样,谢谢!还有@epascarello,是的,它非常具体..

标签: javascript jquery json


【解决方案1】:

您已经尝试过JSON.parse(),这就是答案。

console.log($('#scope').attr('data-json'));

console.log($('#scope').data('json'));

console.log(JSON.parse($('#scope').attr('data-json'))); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scope" data-json='["MIL","QPL"]'></div>

【讨论】:

  • 是的,谢谢!正如我对 Mathijs 所说,我不小心用我在项目中使用的值记录了其他内容,这就是我认为它无法正常工作的原因。
  • @NoahFenghom 酷,乐于助人
【解决方案2】:
var article = document.getElementById('scope');
var dataset = article.dataset.json;
JSON.parse(dataset);

【讨论】:

    【解决方案3】:

    完全不考虑 jQuery,我们得到与 .data() 相同的结果:

    var json    = document.getElementById('scope').getAttribute('data-json');
    var decoded = JSON.parse(json);
    
    console.log("JS-only:");
    console.log(decoded);
    
    console.log("jQuery:");
    console.log($('#scope').data('json'));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="scope" data-json='["MIL","QPL"]'></div>

    【讨论】:

    • getAttribute 是否优于 dataSet
    • 只是不同。 getAttribute() 在旧版浏览器中可用,因此目前它是一种更通用的方法。
    • 旧版浏览器? IE11 支持dataSet,并且从 IE6 开始部分支持...developer.mozilla.org/docs/Web/API/HTMLElement/dataset
    • 不知道它在旧版 IE 中的可用性。 MDN 和“我可以使用...”仅列出 IE 11。caniuse.com/#feat=dataset
    • (另请参阅关于IE 9 中缺少dataSet 等的SO 问题)
    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多