Any way to simplify this code?

前端 未结 4 1986
悲哀的现实
悲哀的现实 2020-12-20 07:38

New to javascript! This works, but I have a lot more to do, and it would be great if there was a cleaner way to do this.. open to using jquery if neccesary :)

(stack

相关标签:
4条回答
  • 2020-12-20 08:10
    var answer = 0;
    for(var i = 1; i <= 20; i++) {
     answer += parseInt(document.getElementById("backer-prediction-" + i).value), 10);
    }
    
    document.getElementById("backer-prediction-answer").value = answer;
    
    0 讨论(0)
  • 2020-12-20 08:24

    The cleanest way to go about this would be to give each of the backer-prediction-# elements a class and grab all of them:

    var backerEls = document.querySelectorAll('.backer-prediction');
    //Get a list of all the elements with the class 'backer-prediction'
    var backers = 0;
    //Total
    for (var i = 0; i < backerEls.length; i++) {
        //Loop over the elements
        backers += parseInt(backerEls[i].value, 10);
        //Parse their values and add them to the total
    }
    
    console.log(backers);​
    

    (Demo)

    This lets you have as many elements as you want without having to update your JS at all.

    0 讨论(0)
  • 2020-12-20 08:26

    You can use the following code to get the backers total.

    function apply(){
        var answer = getBackers();
        document.getElementById("backer-prediction-answer").value = answer;
    }
    
    function getBackers()
    {
        var baseName = "backer-prediction-";
        var elementId = "";
        var backers = 0;
        for(var i = 1; i < 20; i++)
        {
            elementId = baseName + i;
            backers = backers + getElementValue(elementId);
        }
    
        return backers;
    }
    
    function getElementValue(elementId)
    {
        var value = document.getElementById("backer-prediction-1").value;
        return parseInt(value, 10);
    }
    
    0 讨论(0)
  • 2020-12-20 08:37

    I'd do it something like this:

    function apply() {
        var backers = 0;
        for (var i = 1; i < 20; ++i) {
            backers +=
                parseInt(document.getElementById("backer-prediction-" + i).value);
        }
        document.getElementById("backer-prediction-answer").value = backers;
    }
    
    0 讨论(0)
提交回复
热议问题