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