微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 JavaScript 向网页添加文本内容单击按钮后?

如何解决如何使用 JavaScript 向网页添加文本内容单击按钮后?

const displayMessage = function (message) {
  document.querySelector('.message').textContent = message;
};

const displayOtherMessage = function (message) {
  document.querySelector('.otherMessage').textContent = message;
};

document.querySelector('.metric').addEventListener('click',function () {
  document.querySelector('.enterheight').textContent =
    'Enter your height in metres.';
  const height = Number(document.querySelector('.height').value);
  console.log(height,typeof height);
  const weight = Number(document.querySelector('.weight').value);
  console.log(weight,typeof weight);
  if (!height && !weight) {
    document.querySelector('.message').textContent =
      'No height or weight entered.';
  } else if (height && weight) {
    const bmi = weight / height ** 2;
    document.querySelector('.message').textContent = `Your BMI is ${bmi}`;
    if (bmi < 18.5) {
      displayOtherMessage('You are underweight.');
    } else if (bmi >= 18.5 && bmi < 25) {
      displayOtherMessage('You are a healthy weight.');
    } else if (bmi >= 25 && bmi < 30) {
      displayOtherMessage('You are overweight.');
    } else if (bmi >= 30 && bmi < 35) {
      displayOtherMessage('You are obese.');
    } else if (bmi > 35) {
      displayOtherMessage('You are morbidly obese.');
    } else {
      displayOtherMessage('');
    }
  }
});
<!DOCTYPE html>
<html lang="en">
  <head>
    <Meta charset="UTF-8" />
    <Meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <Meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css?family=Amatic+SC"
    />
  </head>

  <body>
    <main>
      <h2>BMI Calculator</h2>
      <h3>Would you like to use metric or imperial values?</h3>
      <div>
        <button id="metric" class="metric">Metric</button>
        <button id="imperial" class="imperial">Imperial</button>
      </div>
      <p id="enterheight"></p>
      <input type="number" class="height" />
      <p id="enterweight"></p>
      <input type="number" class="weight" />
      <p class="message"></p>
      <p class="otherMessage"></p>
    </main>
    <script src="script.js"></script>
  </body>
</html>

我正在用 JavaScript 构建 BMI 计算器,它最终将能够采用公制和英制值。单击“公制”按钮时,我希望文本“以米为单位输入您的高度”出现在高度输入字段上方。这是 JavaScript:

基本上,我的问题是:

document.querySelector('.enterheight').textContent =
    'Enter your height in metres.';

目前,当点击度量按钮时,没有任何反应。控制台说 document.querySelector(...) 为空,我不明白为什么。是因为 HTML 是一个空字符串,还是我在这里遗漏了什么?

解决方法

想想看,HTML 中不存在 DOM 元素。这就是JS无法访问的原因。你需要创建一个像

这样的元素
<p class="enterHeight"></p>

在 HTML 文件中,然后您可以访问它..

希望对你有用...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。