【问题标题】:creating a log with append使用附加创建日志
【发布时间】:2014-09-30 05:17:19
【问题描述】:

需要创建一个消息日志,其中消息与时间一起保存。

我有这个代码,但是新消息被删除了旧的并被新的替换。

var textons = prompt("Digite sua mensagem para a ONS", "");
    var areaons = prompt("Digite a area onde o problema ocorreu", "");



    var date = new Date();
    var d  = date.getDate();
    var day = (d < 10) ? '0' + d : d;
    var mes = date.getMonth() + 1;
    var month = (mes < 10) ? '0' + mes : mes;
    var yy = date.getYear();
    var year = (yy > 100) ? yy - 100 : yy;
    var hours = date.getHours();
    var min = date.getMinutes();
    var minutes = (min < 10) ? '0' + min : min;
    var sec = date.getSeconds();
    var seconds = (sec < 10) ? '0' + sec : sec;     


    if (areaons != null && textons != null) {
        document.getElementById("logdescricao").innerHTML =
        "ONS: " + textons;
        document.getElementById("logarea").innerHTML =
        areaons;

        document.getElementById("loghoracos").innerHTML =
        day + "/" + month + "/" + year + " " + hours + ":" + minutes + ":" + seconds;

        document.getElementById("loghoralocal").innerHTML =
        day + "/" + month + "/" + year + " " + hours + ":" + minutes + ":" + seconds;
    }
}

我想过使用.append(函数)但没有成功。

如何使文本停止被重写并通过保存?

谢谢

【问题讨论】:

    标签: javascript logging innerhtml


    【解决方案1】:

    如果我对您的理解正确,您只是希望它添加到每个部分而不是覆盖? 那么你所要做的就是“+=”而不是“=”

    document.getElementById("logdescricao").innerHTML += "ONS: " + textons
    

    但是,这可能不是最好的方法。

    你可以试试:

    var logdescricaoText = document.createTextNode("ONS: "+textons);
    document.getElementById("logdescricao").appendChild(logdescricaoText);
    

    但是,实际上,如果您想列出事物,那么您应该使用表格。这将允许更整洁和结构化的样式。 在您的 HTML 中:

    <table>
        <thead>
            <tr>
                <td>Descricao</td>
                <td>LogMessage</td>
                <!-- other field headers like 'time' -->
            </tr>
        </thead>
        <tbody id=logs>
        </tbody>
    </table>
    

    然后你可以使用javascript(在你的'if'块内,而不是你所有的“.innerHTML =”东西)

    var logLine = document.createElement("tr");
    document.getElementById("logs").appendChild(logLine);
    
    var descricao = document.createElement("td");
    descricao.appendChild(document.createTextNode("ONS: "+textons));
    logLine.appendChild(descricao);
    
    var logArea = document.createElement("td");
    logArea.appendChild(document.createTextNode(areaons);
    logLine.appendChild(logArea);
    etc..
    

    此外,您可能希望将 CSS 样式应用于 HTML 的“头”部分

    例如。在您的 CSS 文件中:

    thead {
        font-weight: bold;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-03
      • 2012-05-28
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 2019-12-06
      • 2017-01-31
      • 2019-05-24
      相关资源
      最近更新 更多