【问题标题】:Get key value from a HTML attribute array javascript从 HTML 属性数组 javascript 中获取键值
【发布时间】:2019-03-04 12:32:44
【问题描述】:

这是 HTML 属性:

data-plugin-options="{'Enabled': true, 'StartAt': 30, 'EndAt': 65}"

如何通过键名通过javascript获取键的值?比如'StartAt'值。

【问题讨论】:

标签: javascript jquery attr


【解决方案1】:

请看下面的代码。我们知道 singleQuote 在解析 JSON 时会给你一个错误。所以我用 doubleQuote 替换它。

$(document).ready(function(){
var d=$("#data").attr('data-plugin-options');
d=d.replace(/'/g, '"');
var parsedData=JSON.parse(d);
console.log(parsedData.StartAt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id='data' data-plugin-options="{'Enabled': true, 'StartAt': 30, 'EndAt': 65}">Some text...</p>

【讨论】:

  • 如果你使用jQuery,你应该只使用.data函数而不是.attr('data-
【解决方案2】:

元素中的数据总是一个字符串,但是你可以解析它,没问题。

下面是一个例子

const myElement = document.querySelector('p') // here you have element object, you can use other ways to get it
const dataString = myElement.dataset.pluginOptions // here you have string of the data
const formattedDataString = dataString.replace(/'/g, '"') // your JSON is wrongly formatted, this is fix
const dataObject = JSON.parse(formattedDataString) // where you have object of the data
const dataValue = dataObject.Enabled // where you have value by key

您的 JSON 格式也错误,它有单引号,而 JSON 规范需要双引号。您可以替换它,但如果内容包含双引号,这可能会带来额外的问题 - 它会使您的脚本崩溃。我建议查看 JSON 生成并尽可能将其更改为标准。

希望对你有帮助

【讨论】:

  • 它给了我一个错误:SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data in the line of "dataObject"
  • 对不起,我现在测试了一下,修改了代码。但至少在 Firefox 中的问题是,您的 JSON 字符串不符合规范。在 JSON 中,属性必须用双引号括起来,这里是单引号。
  • 谢谢,但由于未定义“pluginOptions”,会打印错误。
  • 您至少可以粘贴完整的元素吗?必须修改第一行才能找到您的元素,否则它将不起作用。
猜你喜欢
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-03
  • 2020-03-26
  • 2011-04-12
  • 1970-01-01
相关资源
最近更新 更多