Javascript函数打印到相同的Span元素

时间:2016-10-01 10:39:30

标签: javascript html

初学者Javascript学生并坚持希望简单的事情。

我有两个按预期工作的javascript函数,但即使它们具有不同的ID,也会打印到相同的Span元素。

无法在SO或谷歌的任何地方找到解决方案。

很抱歉这是很多代码,不知道如何显示它。

https://jsfiddle.net/KrnRbts/dmeztkr0/

非常感谢任何帮助,为SO欢呼!

JAVASCRIPT 1:

function calculateHeliSubTotal() {
    var adultCountHeli = document.getElementById("adultCountHelicopter"),
        childCountHeli = document.getElementById("childCountHelicopter"),
        infantCountHeli = document.getElementById("infantCountHelicopter"),
        adultCostHeli = 230,
        childCostHeli = 160,
        infantCostHeli = 0
    showSpan = document.getElementById('subTotalHelicopter');

    //changes the sub-total if the User changes the adult quantity
    function runAdultCountHeliEvent() {
        adultCountHeli.addEventListener('change', function () {
            getHeliSubTotal();
        });
    }

    //changes the sub-total if the User changes the child quantity
    function runChildCountHeliEvent() {
        childCountHeli.addEventListener('change', function () {
            getHeliSubTotal();
        });
    }

    //changes the sub-total if the User changes the infant quantity
    function runInfantCountHeliEvent() {
        infantCountHeli.addEventListener('change', function () {
            getHeliSubTotal();
        });
    }

    //calls to run the functions
    getHeliSubTotal();

    //a function that is used to run all of the events
    function runHeliEvents() {
        runAdultCountHeliEvent();
        runChildCountHeliEvent();
        runInfantCountHeliEvent();
    }

    //calls to run the functions
    runHeliEvents();

    //calculates the subtotal for the current service
    function getHeliSubTotal() {
        var adultHeliSubTotal = adultCountHeli.value * adultCostHeli,
            childHeliSubTotal = childCountHeli.value * childCostHeli,
            infantHeliSubTotal = infantCountHeli.value * infantCostHeli
        heliSubTotal = adultHeliSubTotal + childHeliSubTotal + infantHeliSubTotal;
        showSpan.innerHTML = '$' + heliSubTotal + ' ' + '(ex-GST)';
    }

}

calculateHeliSubTotal();

JAVASCRIPT 2: - 实际上相同但不同的var值。

function calculateFWSubTotal() {
    var adultCountFW = document.getElementById("adultCountFixedWing"),
        childCountFW = document.getElementById("childCountFixedWing"),
        infantCountFW = document.getElementById("infantCountFixedWing"),
        adultCostFW = 530,
        childCostFW = 260,
        infantCostFW = 0
    showSpan = document.getElementById('subTotalFixedWing');

    //changes the sub-total if the User changes the adult quantity
    function runAdultCountFWEvent() {
        adultCountFW.addEventListener('change', function () {
            getFWSubTotal();
        });
    }

    //changes the sub-total if the User changes the child quantity
    function runChildCountFWEvent() {
        childCountFW.addEventListener('change', function () {
            getFWSubTotal();
        });
    }

    //changes the sub-total if the User changes the infant quantity
    function runInfantCountFWEvent() {
        infantCountFW.addEventListener('change', function () {
            getFWSubTotal();
        });
    }

    //calls to run the functions
    getFWSubTotal();

    //a function that is used to run all of the events
    function runFWEvents() {
        runAdultCountFWEvent();
        runChildCountFWEvent();
        runInfantCountFWEvent();
    }

    //calls to run the functions
    runFWEvents();

    //calculates the subtotal for the current service
    function getFWSubTotal() {
        var adultFWSubTotal = adultCountFW.value * adultCostFW,
            childFWSubTotal = childCountFW.value * childCostFW,
            infantFWSubTotal = infantCountFW.value * infantCostFW
        FWSubTotal = adultFWSubTotal + childFWSubTotal + infantFWSubTotal;
        showSpan.innerHTML = '$' + FWSubTotal + ' ' + '(ex-GST)';
    }

}

calculateFWSubTotal();

3 个答案:

答案 0 :(得分:2)

showSpan在您的变量声明中是全局的,因为您缺少逗号。

function calculateHeliSubTotal() {
  var adultCountHeli = document.getElementById("adultCountHelicopter"),
    childCountHeli = document.getElementById("childCountHelicopter"),
    infantCountHeli = document.getElementById("infantCountHelicopter"),
    adultCostHeli = 230,
    childCostHeli = 160,
    infantCostHeli = 0 // no comma, so a semicolon is automatically inserted
  showSpan = document.getElementById('subTotalHelicopter'); //global
// ...
}

function calculateFWSubTotal() {
  var adultCountFW = document.getElementById("adultCountFixedWing"),
    childCountFW = document.getElementById("childCountFixedWing"),
    infantCountFW = document.getElementById("infantCountFixedWing"),
    adultCostFW = 530,
    childCostFW = 260,
    infantCostFW = 0 //no comma, so javascript inserts a semicolon
  showSpan = document.getElementById('subTotalFixedWing'); //showSpan is overwritten

// ...
}

在两个方法中添加一个逗号,然后就完成了设置。

更新了小提琴:https://jsfiddle.net/dmeztkr0/1/

以下是有关JavaScript自动分号插入规则的一些信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion

答案 1 :(得分:1)

之后缺少逗号
infantCostHeli = 0

所以js引擎正在推出一个&#39 ;;'在它之后。下一行是:

showSpan = document.getElementById('subTotalHelicopter');

将被解释为一个新的单一陈述:因此showSpan声明缺少一个' var' identifier:所以showSpan变量现在是一个全局变量,附加到window对象。

可悲的是,使用infantCostFW变量的第二个函数中存在同样的错误:

infantCostFW = 0

所以第二个函数也引用了那个全局变量,而不是一个本地作用域,新创建的' showSpan'变种。

因此,对calculateFWSubTotal()的调用会覆盖showSpan全局变量值,然后两个方法在附加到某些DOM节点中的更改事件的侦听器触发时使用该变量。第一个函数中的事件处理程序在calculateHeliSubTotal()之后触发,并且它们正在使用全局变量,因此将showSpan定义为

showSpan = document.getElementById('subTotalHelicopter');

对calculateHeliSubTotal(。)

中定义的事件侦听器无关紧要

在vars完成之后,只需添加一个额外的逗号。使用像Eslint或JSlint这样的linter会为你节省很多类似的问题。

此外,您的代码中存在许多重复,并且计算值和注册事件处理程序的逻辑实际上是耦合的。我认为你会在代码审查堆栈交换中发布它并寻求一些建议。

答案 2 :(得分:0)

您可以使用传递给函数的配置对象来允许重用。这利用了javascript中的闭包,它将锁定事件监听器周围的环境,因此您可以单独使用它们。

我还做了一些不必要的重构

function calculateSubTotal(config) {
  var
    adultCount = document.getElementById("adultCount" + config.type),
    childCount = document.getElementById("childCount" + config.type),
    infantCount = document.getElementById("infantCount" + config.type),
    showSpan = document.getElementById('subTotal' + config.type),
    adultCost = config.cost.adult,
    childCost = config.cost.child,
    infantCost = config.cost.infant;
  
  // you don't need to wrap these events, you can just call
  // getSubTotal directly on change
  adultCount.addEventListener('change', getSubTotal);
  childCount.addEventListener('change', getSubTotal);    
  infantCount.addEventListener('change', getSubTotal);

  //calculates the subtotal for the current service
  function getSubTotal() {
    var 
      adultSubTotal = adultCount.value * config.cost.adult,
      childSubTotal = childCount.value * config.cost.child,
      infantSubTotal = infantCount.value * config.cost.infant,
      subTotal = adultSubTotal + childSubTotal + infantSubTotal;
    
    showSpan.innerHTML = '$' + subTotal + ' ' + '(ex-GST)';
  }
}

// init the total for helicopters passing in a config object
calculateSubTotal({
  type: 'Heli',
  cost: {
    adult: 230,
    child: 160,
    infant: 0
  }
})

// init the total for the other thing
calculateSubTotal({
  type: 'OtherThing',
  cost: {
    adult: 430,
    child: 160,
    infant: 0
  }
})