簡體   English   中英

JavaScript 不更新 DOM 並導致瀏覽器崩潰

[英]JavaScript not updating the DOM and crashing the browser

我已經為一個按鈕編寫了以下 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
};

網址:

<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>

問題是第二次運行該函數時,全局變量可能已經包含隨機值,因此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
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM