I need to print something into a table using Javascript

时间:2015-05-24 21:00:05

标签: javascript html dom

I need to create a script that with the click of a button collects data from prompts and then prints it into a table. However I can't get the script to work. It collects the data fine, but it won't print it.

function addCard() 
{ 
    var card1 = document.getElementById("name").value;
    var card2 = document.getElementById("cost").value;
    var card3 = document.getElementById("class").value;
    var card4 = document.getElementById("type").value;
    var card5 = document.getElementById("attack").value;
    var card6 = document.getElementById("health").value;
    var cardStats = [card1 + ", " + card2 + ", " + card3 + ", " + card4 + ", " + card5 + ", " + card6];
    var cardList = new Array();
    cardList.push(cardStats);
    alert(cardList);
    cardStats = [];
var textSplit = cardList.split(",");
    var tableElem = document.createElement("table");
    var rowElem;
    var cellElem;
    var cellContent;
    for (var i=0; i< textSplit.length; i++)
    { 
        if (i % 6 == 0)
        {
            rowElem = document.createElement("tr");
            tableElem.appendChild(rowElem);
        };
        cellElem = document.createElement("td");
        cellContent = document.createTextNode(textSplit[i]);
        cellElem.appendChild(cellContent);
        rowElem.appendChild(cellElem);
    }
    var tableContainer = document.getElementById("tableContainer");
    var oldElem = tableContainer.childNodes;
    for (var i = 0; i < oldElem.length; i++) 
    {
        tableContainer.removeChild(oldElem[i]);
    }
    tableContainer.appendChild(tableElem);*/

};

I appreciate any help I can get.

1 个答案:

答案 0 :(得分:1)

On this line:
var cardStats = [card1 + ", " + card2 + ", " + card3 + ", " + card4 + ", " + card5 + ", " + card6];
it looks like you're trying to create an array of cardStats. What is actually happening is that you're creating a single element array with commas separating the values in a single string.

Later, when you're doing the split you're missing the space after the comma that you inserted.

I think that you would probably be able to solve your problem by doing this instead:
var cardStats = [card1, card2, card3, card4, card5, card6];
and then using cardStats in the for loop later on instead of textSplit.

Edit: Also just noticed that you're doing i % 6: that should be i % 5 because i will take the 6 values from 0 to 5 (inclusive) and a value of 6 will never be hit. When i has a value of 5 then it is processing the 6th element in the array.