簡體   English   中英

為什么我的程序不斷創建新元素?

[英]Why does my program keep creating new elements?

這是表單交互性的一部分。

用戶可以從一系列活動中進行選擇。 其中6個活動的定價為100,其中一項定價為200。

當用戶選中這些框時,會出現一個標簽,告訴用戶總價是多少。

目前,價格正在計算中。

但是,每一次選中一個框,都會添加一個NEW標簽。 而不是更新舊的。 為什么會這樣呢?

這是我的代碼:

// Register for Activities section of the form.
document.querySelector(".activities").addEventListener("change", function(){
    var main = document.getElementById("all");
    var framework = document.getElementById("framework");
    var libs = document.getElementById("libs");
    var express = document.getElementById("express");
    var node = document.getElementById("node");
    var build = document.getElementById("build");
    var npm = document.getElementById("npm");

    // Calculate running total of price of events selected
    var mainPrice = 200;
    var otherPrice = 100;
    var totalPrice = 0;
    var totalLabel;


    if(!totalLabel){
        totalLabel = document.createElement('label');
        activities.appendChild(totalLabel);
    }

    if(main.checked == true){
        totalPrice += mainPrice;
    }
    if(framework.checked == true || express.checked == true) {
        totalPrice += otherPrice;
    } 
    if(libs.checked == true || node.checked == true) {
        totalPrice += otherPrice;
    } 
    if(build.checked == true) {
        totalPrice += otherPrice;
    } 
    if(npm.checked == true) {
        totalPrice += otherprice;
    }

    var totalNumber = totalPrice.toString();
    var totalText = "Total is $" + totalNumber;

    totalLabel.innerHTML = totalText;
});

我之前曾以為這是個問題,但我認為只有在totalLabel不存在的情況下,才創建一個新元素來解決此問題:

if(!totalLabel){
        var totalLabel = document.createElement('label');
        activities.appendChild(totalLabel);
    }

有什么建議嗎?

您有范圍問題。 創建時,totalLabel僅存在於函數內部。

將“ var totalLabel”放在函數作用域之外,並從if塊中丟失“ var”。 像這樣:

var totalLabel;
document.querySelector...

您可以嘗試以下方法:

var totalLabel;

totalLabel = document.createElement('label');
activities.appendChild(totalLabel);

document.querySelector(".activities").addEventListener("change", function(){
  // code

  // comment below code
  //if(!totalLabel){
  //  totalLabel = document.createElement('label');
  //  activities.appendChild(totalLabel);
  // }

  // code
});

暫無
暫無

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

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