在javascript中更改按钮文本?

时间:2016-05-22 10:17:03

标签: javascript button text

如何将按钮文本更改为数组结果?

这是我的代码:

var lastLength = bestRes.length;
for( var x = 0; x< lastLength; x++){

    var specMatchTime = new Date(Date.parse(bestRes[x]["match_time"]));
    var specMatchHour = specMatchTime.getHours();
    var specMatchMinutes = specMatchTime.getMinutes();

    var rowDiv = document.createElement("div");
    rowDiv.className += "row";

    var colDiv = document.createElement("div");
    colDiv.className += "col-md-2 matchDetails";
    colDiv.innerHTML = ''+specMatchHour + ":" + specMatchMinutes;
    rowDiv.appendChild(colDiv);

    colDiv = document.createElement("div");
    colDiv.className += "col-md-2 matchDetails";
    colDiv.innerHTML = bestRes[x]['league'];
    rowDiv.appendChild(colDiv);

    colDiv = document.createElement("div");
    colDiv.className += "col-md-4 matchDetails";
    colDiv.innerHTML = bestRes[x]['home']+' vs '+ bestRes[x]['away'];
    rowDiv.appendChild(colDiv);

    colDiv = document.createElement("div");
    colDiv.className += "col-md-1 matchButton";
    var button = document.createElement("button");
    button.className += "btn";
    var moneyHome = bestRes[x]['money_home'];
    moneyHome.toString();
    button.innerHTML = moneyHome;
    colDiv.innerHTML = '<input id="buttonID" type="button" class="btn"/>';
    rowDiv.appendChild(colDiv);
}

此后按钮仍然显示为空白。有什么问题?

1 个答案:

答案 0 :(得分:-1)

一般来说,您应首先在DOM树中找到按钮元素,然后使用innerHTML属性分配新值,例如:

var button = document.getElementById('your-button-id');
button.innerHTML = bestRes[x]['home'];

在您的示例中,尝试以这种方式更改最后一部分:

var button = document.createElement("input");
button.type = "button";
button.id = "buttonID";
button.className = "btn";
button.value = finalRes[x]['money_home'];
colDiv.appendChild(button);
rowDiv.appendChild(colDiv);