当我重新加载页面时,我之前的评论消失了 - 这与本地存储有关

时间:2016-11-15 13:25:59

标签: javascript html

尝试使其在刷新页面时,以前的注释保留在页面上。不太清楚该怎么做。还想知道如何制作它,以便当你点击名字框时,你不必突出显示" name"然后写下你的名字,你可以点击,你写的只是替换"名称"。

//Functions for Homepage
function imgUpdate() {
    var img = document.getElementById("navImg").alt;
        if (img === "Cat Selfie") {
            document.getElementById("navImg").src = "foo.jpg";
            document.getElementById("navImg").alt = "foo"
        }
        else {
        document.getElementById("navImg").src = "cat-selfie.jpg";
        document.getElementById("navImg").alt = "Cat Selfie"
        }
}

//Functions for Comments
function clearComment(){
    $('#txt1').val(''); //short for getElement when using j query
};

function clearName(){
    $('#namebox').val('');
};

function saveComment() {
    var ctext = $('#txt1').val();
    var cname = $('#namebox').val();
    if (cname === 'Name') {cname = 'Anon';}
    alert('saveComment cname=' + cname + ' ctext=' +ctext);
    var d = Date();
    var prevComments = $('#cmtlist').html();
    var curComment='<p><span class="cmtname">'+cname+ ':' + '</span>'
        +ctext +d+' </p>'; //span = add things to something  inline
    curComment += prevComments;
        $('#cmtlist').empty();
        $('#cmtlist').append(curComment);
    clearComment();
    clearName();

    setObject('totCmts', curComment);
}



function fetchComments(){
    var inlist=getObject('totCmts');
        if(inlist === null){
            inlist='';
        }
    //display the comments
        $('#cmtlist').empty();
        $('#cmtlist').append(inlist);
}

我的Html文件

<html>
<head>
<meta charset="utf-8" />
<title>Dubya comments</title>
<link rel="stylesheet" href="homepage.css" type="text/css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="homepage.js"></script>
</head>
<body>
<header id="banner">
</header>
<nav>
<button type="button" onclick="clearComment()">Clear
comment</button> 
<button type="button" onclick="saveComment()">Save comment</button>
</nav>
<div id="main">
<div id="dtext">
<h4>Your comment</h4>
<input id="namebox" type="text" maxlength="32" size="20"
value="Name" />
<br />
<textarea id="txt1" class="textbox" rows="6"></textarea>
</div>
<h4>Comments</h4>
<div id="cmtlist"></div>
</div>
</body>

</html>

1 个答案:

答案 0 :(得分:2)

杰克,您可以使用如下全局对象轻松地将数据存储在localStorage中:

// your array with comments
var comments = ["First comment", "Second comment"];

// saving your comments in JSON format
window.localStorage.setItem("comments", JSON.stringify(comments));

// retrieving them
comments = JSON.parse(window.localStorage.getItem("comments"));

您可以在MDN

上详细了解localStorage