无法在表格中添加按钮

时间:2014-07-14 18:18:02

标签: javascript

我正在尝试使用javascript向表格添加几个按钮,但我会继续使用[objectHTMLInputElement]

提供此结果

enter image description here

这是我的代码:

function createDiseaseTable(country){
    var displayCountry = document.getElementById("countrySelected");
    displayCountry.innerHTML = country.name;
    var diseaseTable = document.getElementById("diseases");
    diseaseTable.innerHTML = "";
    for (var i = 0; i<country.diseases.length; i++) ////////////////////////////////////
    {
        var changeDisease = document.createElement('input');
        changeDisease.type = 'button';
        changeDisease.name = "x"
        changeDisease.onclick = hi();
        var row = diseaseTable.insertRow(i);
        var cell1 = row.insertCell(0)
        var cell2 = row.insertCell(1)
        var cell3 = row.insertCell(2)
        var cell4 = row.insertCell(3)
        var cell5 = row.insertCell(4);
        cell1.innerHTML = OurDiseases[i].name;
        cell2.innerHTML = OurDiseases[i].cureLevel;
        cell3.innerHTML = OurDiseases[i].killLevel;
        cell4.innerHTML = OurDiseases[i].cured;
        cell5.innerHTML = changeDisease;
        console.log(changeDisease);
    }
    var row = diseaseTable.insertRow();
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    var cell5 = row.insertCell(4);
    cell1.innerHTML = "Disease";
    cell2.innerHTML = "Level needed to cure";
    cell3.innerHTML = "Deaths each year";   
    cell4.innerHTML = "Cured";
    cell5.innerHTML = "More Info";

}

注意:我不担心点击后还没有运行功能,我只想要显示实际的按钮

2 个答案:

答案 0 :(得分:2)

您需要使用appendChild功能

你的代码可能看起来像这样:

...
cell5.appendChild(changeDisease);
...

您可以在此处找到有关此功能的更多详细信息:http://www.w3schools.com/jsref/met_node_appendchild.asp

更新 - 请参阅评论:

name是元素的属性,而不是按钮的标题,如果您想设置标题,请使用属性value - 这是一个示例:http://www.w3schools.com/html/tryit.asp?filename=tryhtml_button < / p>

答案 1 :(得分:0)

自从我在没有jQuery的情况下完成DOM操作以来已经很长时间了,但我相信你需要做cell5.appendChild(changeDiseas)而不是.innerHTML(期待一个HTML字符串)。< / p>

http://www.w3schools.com/jsref/met_node_appendchild.asp