javascript - 我需要通过按下 Javascript 中的按钮来修改和更新值
问题描述
我获取数据,使其成为一个对象并打印它的属性。然后我需要更新 sensor.value - 如果 readonly 为 false - 按下按钮,使其从 true 变为 false,反之亦然。我该怎么做?
索引.html
<head>
<link rel="stylesheet" href="style.css" />
<meta charset="UTF-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0" />
<title>Sensors</title>
</head>
<body>
<h1>Sensors</h1>
<div class="container" id="container"> </div>
<script src="sensor.js"></script>
<script src="script.js"></script>
</body>
脚本.js
const container = document.getElementById("container");
// api url
const api_url =
"https://hf3xzw.deta.dev/";
// Defining async function
fetch(api_url)
.then((r) => r.json()) // (1)
.then((body) => {
for (let index = 0; index < 8; index++) {
const sensor = JSONToSensor(body["sensors"][index]);
let newCard = document.createElement("div");
newCard.classList.add("card");
newCard.innerHTML = `<br>
<h2><span style="font-weight: normal;">Description: </span>${sensor.description}</h2>
<h2><span style="font-weight: normal;">ID: </span>${sensor.id}</h2>
<h2><span style="font-weight: normal;">Lat: </span>${sensor.lat}</h2>
<h2><span style="font-weight: normal;">Lng: </span>${sensor.lng}</h2>
<h2><span style="font-weight: normal;">Place: </span>${sensor.place}</h2>
<h2><span style="font-weight: normal;">Read Only: </span>${sensor.readonly}</h2>
<h2><span style="font-weight: normal;">State Code: </span>${sensor.state_code}</h2>
<h2><span style="font-weight: normal;">Value: </span>${sensor.value}</h2>
`;
container.appendChild(newCard);
}
});
编辑:忘记重写我为使其工作所做的尝试。
第一次尝试
<button type="button" onclick="document.getElementById('container').innerHTML = 'Hey There'">Try it</button>
第二次尝试
if (sensor.readonly == false) {
let btn = document.createElement("button");
btn.innerHTML = "Change value";
btn.onclick = function () {
change();
}
container.appendChild(btn);
}
function change() {
if (sensor.value == true)
sensor.value == false;
else
sensor.value == true;
container.appendChild(newCard);
}
我见过类似的东西并试图实现,但我真的不明白我在做什么
解决方案
推荐阅读
- c - 我一直在尝试使用 VSCODE 编写 c 代码,但无法正常工作
- python - standard_init_linux.go:219: exec 用户进程导致:exec 格式错误
- list - 从 Ocaml 中的列表列表中删除重复项?
- azure-devops - Azure Devops:代理在不同的构建中跳跃
- javascript - 如何在 Node.js 中重写对象或类的默认表示?(就像 Python 的 __str__ 和 __repr__ 一样)
- python - 在 Tensorflow 中使用 AUTOTUNE 时出现属性错误?
- python - 理解调用的实现
- javascript - 如何在 O(n) 时间内循环使用包含数组的对象的数组?
- c++ - OpenGL/GLSL 4.5 - 在默认 FBO 中使用 MRT
- ruby - 通过 HTTPS 代理进行 HTTPS 请求的法拉第代码