如何从textarea保存到localStorage?

时间:2011-10-25 16:23:30

标签: javascript html5 google-chrome-extension local-storage

我正在尝试在localStorage中保存输入到textarea的电子邮件。当我加载页面时,我看到占位符“你的gmail地址”,但当我输入一个值并单击“保存”时,没有任何反应。我没有看到警报或控制台验证文本是否已保存。我做错了什么?

<html>
<head><title>Extension Options</title></head>
<body>
<textarea id="user" style="margin-bottom: 4px; width: 250px; height: 20px">
</textarea><br />
<button id="save">Save</button>
<!--<button id="save">Clear</button>-->

<script type="text/javascript">

//check if "user" is in localStorage

if (localStorage["user"])
{
    var user = localStorage["user"] ;
    document.getElementById("user").value = user ;
    alert("you are already a user")
}
else
{
    document.getElementById("user").placeholder = "your gmail address" ;
    console.log("user no found in localStorage")
}

//save entered gmail address
document.getElementById("save").addEventListener
{
    "click", function ()
    {
        var user = document.getElementById("user").value ;
        //localStorage["user"] = user ;
        localStorage.setItem("user", user) ;
        alert("gmail id saved") ;
        console.log("gmail id saved")
    } , false
}

</script>
</body>
</html>

1 个答案:

答案 0 :(得分:10)

您的addEventListener函数使用不正确。它应该像这样使用:

document.getElementById("save").addEventListener("click", function ()
    {
        var user = document.getElementById("user").value ;
        //localStorage["user"] = user ;
        localStorage.setItem("user", user) ;
        alert("gmail id saved") ;
        console.log("gmail id saved")
    } , false);

MDN docs on element.addEventListener

Working demo with your code