【问题标题】:Replace existing content = local storage + existing content. Javascript, WebStorage, LocalStorage替换现有内容 = 本地存储 + 现有内容。 Javascript,网络存储,本地存储
【发布时间】:2013-08-04 08:46:54
【问题描述】:

嗯,我试图将“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,所以我想用 textBox.value + logContent 中的原始内容替换“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.
}
}

【问题讨论】:

    标签: javascript html local-storage web-storage


    【解决方案1】:

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

    ....
    
    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);
        }
    }
    

    【讨论】:

    • 非常感谢,这正是我想要的。
    • 很高兴我能帮上忙!如果您要更频繁地执行此类操作,您可能需要查看诸如AngularJS 之类的数据绑定框架。 Angular 与 localStorage (github.com/gsklee/ngStorage) 集成得很好,但类似的框架提供了类似的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    相关资源
    最近更新 更多