从HTML属性数组javascript获取键值

问题描述 投票:1回答:2

这是HTML属性:

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

如何通过密钥名称获取密钥的值?比如'StartAt'值。

javascript jquery attr
2个回答
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>

0
投票

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

这是一个如何做到的例子

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生成并尽可能将其更改为标准。

希望这可以帮助

© www.soinside.com 2019 - 2024. All rights reserved.