当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Json数组转换字符串、字符串转换原数组......

Json数组转换字符串、字符串转换原数组......

2019年03月20日  | 移动技术网IT编程  | 我要评论
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<style>
*{
margin: 0;
padding: 0;
}
.div2{
width: 400px;
height: 250px;
border: 1px solid red;
}

.div2 li{

list-style: none;
float: left;
width: 85px;
height: 25px;
background-color: lightgray;
margin-left:12px ;
margin-top: 30px;
text-align: center;
cursor: pointer;
}
.div3 {
width: 300px;
height: 100px;
border: 1px solid red;
position: absolute;
right: 300px;
top: 100px;
}

</style>
</head>
<body>
<div class="div2">
<ul id="ul">

</ul>
</div>
<div class="div3">
标题:<input type="text" id="title"><br>
颜色:<input type="text" id="color"><br>
字体:<input type="text" id="size"><br>
<input type="button" value="添加" onclick="f1()"><br>

</div>
</body>
</html>
<script>
var array=[];
function f1(){

//获取输入的颜色
var color=document.getelementbyid("color").value;
//获取输入的标题
var title=document.getelementbyid("title").value;
//获取输入的字体
var size=document.getelementbyid("size").value;

var item={
title:title,
color:color,
size:size
};

array.push(item);
var str="";

for( var i=0;i<array.length;i++){
str+="<li style='color:"+array[i].color+";font-size:"+array[i].size+"'>" +array[i].title + "</li>";
}

var ul=document.getelementbyid("ul");
ul.innerhtml=str;

//更新存储
var str= json.stringify(array);
localstorage.setitem("key1",str);
}

//将读取出来的json字符串在转成原数组
var jstr= localstorage.getitem("key1");

var array=json.parse(jstr);
var str="";

for( var i=0;i<array.length;i++){
str+="<li style='color:"+array[i].color+";font-size:"+array[i].size+"'>" +array[i].title + "</li>";
}

var ul=document.getelementbyid("ul");
ul.innerhtml=str;
</script>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网