更改 HTML5 自定义数据属性中的 div 内容

我在 file1.html 中声明了以下 div 来绘制一个漂亮的仪表。div 使用一些 HTML5 自定义数据属性,如下所示:


<div class="gauge" id="meter1" data-settings='

   {"value": 7,

    "min": 0,

    "max": 50,

    "threshold": [

      {"from": 25, "to": 50, "color": "blue", "label": "Warning"},

      {"from": 0, "to": 25, "color": "orange", "label": "Critical"}

        ]

    }'></div>

现在在 Javascript 中,如何调用 div 并为“value”属性和“threshold”属性设置新数字?谢谢


LEATH
浏览 137回答 2
2回答

www说

您可以使用以下功能来完成您的任务:element.getAttribute获取属性内的值element.setAttribute设置属性内的值JSON.stringify并JSON.parse使用 JSON检查下面的代码。var meter1 = document.getElementById("meter1")var dataSettings = JSON.parse(meter1.getAttribute("data-settings"))dataSettings.value = 8dataSettings.min = 5meter1.setAttribute("data-settings", JSON.stringify(dataSettings))console.log(meter1.getAttribute("data-settings"))<div class="gauge" id="meter1" data-settings='&nbsp; &nbsp;{"value": 7,&nbsp; &nbsp; "min": 0,&nbsp; &nbsp; "max": 50,&nbsp; &nbsp; "threshold": [&nbsp; &nbsp; &nbsp; {"from": 25, "to": 50, "color": "blue", "label": "Warning"},&nbsp; &nbsp; &nbsp; {"from": 0, "to": 25, "color": "orange", "label": "Critical"}&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; }'></div>

杨魅力

您可以document.querySelector使用JSON.parseconst gauge = document.querySelector('#meter1');&nbsp;console.log(JSON.parse(gauge.dataset.settings).threshold)<div class="gauge" id="meter1" data-settings='&nbsp; &nbsp;{"value": 7,&nbsp; &nbsp; "min": 0,&nbsp; &nbsp; "max": 50,&nbsp; &nbsp; "threshold": [&nbsp; &nbsp; &nbsp; {"from": 25, "to": 50, "color": "blue", "label": "Warning"},&nbsp; &nbsp; &nbsp; {"from": 0, "to": 25, "color": "orange", "label": "Critical"}&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; }'></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript