我们如何将字符串存储在localStorage中? [英] How do we store a string in 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屋!