I declare a following div in file1.html to draw a nice gauge. The div uses some HTML5 Custom Data Attributes as follow:
<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>
Now in Javascript, how do I recall the div and set new number for the "value" attribute and "threshold" attribute? Thanks
You can use document.querySelector
with JSON.parse
const gauge = document.querySelector('#meter1'); console.log(JSON.parse(gauge.dataset.settings).threshold)
<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>
You can use following functions to fulfill your task:
element.getAttribute
to get the values inside the attribute element.setAttribute
to set the values inside the attribute JSON.stringify
and JSON.parse
to work with JSON Check the code below.
var meter1 = document.getElementById("meter1") var dataSettings = JSON.parse(meter1.getAttribute("data-settings")) dataSettings.value = 8 dataSettings.min = 5 meter1.setAttribute("data-settings", JSON.stringify(dataSettings)) console.log(meter1.getAttribute("data-settings"))
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.