首页 > 解决方案 > 我需要通过按下 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);
}

我见过类似的东西并试图实现,但我真的不明白我在做什么

标签: javascripthtml

解决方案


推荐阅读