替换现有内容=本地存​​储+现有内容。 Javascript,WebStorage,LocalStorage

时间:2013-08-02 23:47:02

标签: javascript html html5 local-storage web-storage

我试图将“textBox”中的消息保存回localStorage并将其添加到“logContent”,但是当我刷新页面时,“logContent”仍为空,只有原始内容存在。

<body>

<div class="modal-body"> 
    <input id="textBox" type="text" placeholder="Type Message" onkeydown="if (event.keyCode == 13) {enterPressed();}">
    <p id="logContent">
            -- Logging is created --
    </p>
</div>

</body>

这是我的Javascript,所以我想用logBox中的textBox.value +原始内容替换“logContent”中的原始内容,并且即使刷新页面也要一直显示所有内容。谢谢。

var today = new Date(); 
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0
var yyyy = today.getFullYear();

if (dd < 10) {
dd ='0'+ dd
} 

if (mm < 10) {
mm ='0'+ mm
} 

today = dd + '/' + mm + '/' + yyyy;

function enterPressed() {
localStorage.setItem("logs", document.getElementById("textBox").value);
if (textBox.value == "") {

}
else {
var logText = today + ":" + " " + localStorage.getItem("logs") + '<br>';
$("#logContent").prepend(logText); // Prepend textBox's content to the top of  "logContent".
textBox.value = ""; // To clear the textBox after enter is pressed.
}
}

1 个答案:

答案 0 :(得分:0)

原始脚本没有提供从localStorage加载日志的方法,并且在“logs”键下存储了新输入,而意图是预先添加。解决方案非常简单:在页面加载时从localStorage加载,并使用页面上显示的localStorage['logs']内容覆盖logContents

....

window.onload = function(){
    existing_log = localStorage.getItem("logs");
    console.log(existing_log);
    if (existing_log){document.getElementById("logContent").innerHTML = existing_log;}
}

function enterPressed() {
    if (textBox.value == "") {
        return;
    }
    else {
        var logText = today + ":" + " " + document.getElementById("textBox").value + '<br>\n';
        $("#logContent").prepend(logText); // Prepend textBox's content to the top of  "logContent".
        textBox.value = ""; // To clear the textBox after enter is pressed.
        localStorage.setItem("logs", document.getElementById("logContent").innerHTML);
    }
}