我们如何将字符串存储在localStorage中? [英] How do we store a string in localStorage?

查看:134
本文介绍了我们如何将字符串存储在localStorage中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习javascript,xml和html.对于家庭作业,我需要从XML文件的某些节点检索一些数据,将数据连接起来,然后将连接后的字符串存储在localStorage中.我在将串联的字符串存储在localStorage中遇到麻烦.我认为问题出在这两行-

I'm learning javascript, xml, and html. For a homework assignment, I need to retrieve some data from some nodes of a XML file, concatenate the data, and store the concatenated string in localStorage. I am having trouble in storing the concatenated string in localStorage. I believe the issue is in these two lines -

var s_data = localStorage [students];
$(#clickme").text(学生的名字:" + s_data);

var s_data = localStorage[students];
$("#clickme").text("Students' first names: " + s_data);

有人可以看一下并给我一些如何修复它的提示吗?预先感谢您的帮助.

Can someone take a look and give me some tips on how to fix it? Thank you in advance for your help.

    <!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <title>HWK</title>
    <meta charset="UTF-8">  
</head>
<body>
    <div id="clickme" onclick="startAjax()">Click me to see all the students' first names</div>
    <script>
    function startAjax(){
      $("#clickme").text("Calling server");
      $.ajax({url:"hwk.xml",    
      success:callbackFunction, error:errorFunction});
    }

    function callbackFunction(data,info)
    {
        var students = $(data).find("student first_name");

    try {
    if (students && students.length)
      {
        var s_data = localStorage[students];    
        $("#clickme").text("Students' first names: " + s_data);
              }
    }
    catch (e) {
      if (e != window["localStorage"])
        alert("No local storage. Should use cookie instead.");

    }
     }

    function errorFunction(data,info){
    $("#clickme").text("error occurred:"+info);
    }
    </script>
</body>
</html>

推荐答案

您可以使用 localStorage getItem()进行检索

You can use the setItem() to set a value to the localStorage and getItem() to retrieve it

例如:

localStorage.setItem('mykey', 'somevalue')

演示:小提琴

这篇关于我们如何将字符串存储在localStorage中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆