【问题标题】:JavaScript not updating the DOM and crashing the browserJavaScript 不更新 DOM 并导致浏览器崩溃
【发布时间】:2021-07-02 14:31:35
【问题描述】:

我为单击时调用函数的按钮编写了以下 HTML,并且函数的输出写入 DOM 中的 div 中。但它无论如何都不会更新 DOM,而是冻结整个浏览器选项卡以及 HTML 页面。请帮忙。

提前谢谢你

let rows = [];
let cols = [];
let secKey = "";
const generateKey = () => {
  var count = 0;
  while (count != 5) {
    let randomNumber = Math.floor((Math.random() * 10));
    if (!rows.includes(randomNumber)) {
      rows.push(randomNumber);
      count++;
    }
  }
  count = 0;
  while (count != 6) {
    let randomNumber = Math.floor((Math.random() * 10));
    if (!cols.includes(randomNumber)) {
      cols.push(randomNumber);
      count++;
    }
  }
  // put on the document
  secKey = `${cols[0]}${rows[0]}${cols[1]}${rows[1]}${cols[2]}${rows[2]}${cols[3]}${rows[3]}${cols[4]}${rows[4]}${cols[5]}`;
  document.querySelector("#sec-key").innerHTML = `Your secret key is <strong id="sec-key">${secKey}</strong>`; // #sec-key is a div where I want to show the output
};

HTML:

<div class="key-container">
  <button id="generate-key" class="util-btn" onclick="generateKey()">Generate new secret key</button>
  <p class="key-holder" id="sec-key">
    <!--output is expected here-->
  </p>
  <p id="caution">*please remember the secret key for decryption</p>
</div>

【问题讨论】:

  • 警告:不用说,但运行代码 sn-p 并单击按钮可能会使浏览器崩溃。
  • 编辑为不是是一个sn-p

标签: javascript html function google-chrome


【解决方案1】:

问题在于,在第二次运行该函数时,全局变量可能已经包含了随机值,因此 count 变量永远不会递增,并且循环会无限旋转。

要么在函数实现中初始化全局变量,要么使用数组的长度而不是计数器。第二种方法如下所示:

let rows = [];
let cols = [];
let secKey = "";
const generateKey = () => {

  while (rows.length != 5) {
    let randomNumber = Math.floor((Math.random() * 10));
    if (!rows.includes(randomNumber)) {
      rows.push(randomNumber);
    }
  }

  while (cols.length != 6) {
    let randomNumber = Math.floor((Math.random() * 10));
    if (!cols.includes(randomNumber)) {
      cols.push(randomNumber);
    }
  }
  // put on the document
  secKey = `${cols[0]}${rows[0]}${cols[1]}${rows[1]}${cols[2]}${rows[2]}${cols[3]}${rows[3]}${cols[4]}${rows[4]}${cols[5]}`;
  document.querySelector("#sec-key").innerHTML = `Your secret key is <strong id="sec-key">${secKey}</strong>`; // #sec-key is a div where I want to show the output
};

【讨论】:

  • 我已经把数组从全局初始化改成本地了,死循环错误解决了,但是还是无法修改DOM。
猜你喜欢
  • 2014-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多