代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <head> <title>javascript操作Json数据_www.jb200.com</title> <style type="text/css"> div { padding: 10px; border: solid 1px #222; margin: 5px; font-size: 12px; } </style> <script type="text/javascript"> // 存储用户对象的数据格式 // [ // {'uid':'123','pwd':'123456'}, // {'uid':'124','pwd':'123456'}, // {'uid':'125','pwd':'123456'} // ] function $(obj) { return typeof (obj) == "string" ? document.getElementById(obj) : obj; } var json = [];//申明数字 //添加新用户 function add() { var uid = $('uid').value; var pwd = $('pwd').value; for (var i = 0; i < json.length; i++) { if (json[i].uid == uid) { return; } } json.push({ "uid": uid, "pwd": pwd }); show(json); } //删除用户 function del() { var uid = $('uid').value; for (var i = 0; i < json.length; i++) { if (json[i].uid == uid) { json.splice(i, 1); break; } } show(json); } //更新用户密码 function frs() { var uid = $('uid').value; var pwd = $('pwd').value; for (var i = 0; i < json.length; i++) { if (json[i].uid == uid) { json[i].pwd = pwd; break; } } show(json); } //显示用户列表 function show(json) { var html = ""; for (var i = 0; i < json.length; i++) { html += "UID:" + json[i].uid + ";PWD:" + json[i].pwd + "/r/n"; } $('t').innerText = html; } </script> </head> <body> <input type="hidden" value="" id="selectedUsers" /> <div> UID:<input type="text" id="uid" /> PWD: <input type="text" id="pwd" /> <a href="javascript:void(0);" title="" onclick="add();">添加用户</a> <a href="javascript:void(0);" title="" onclick="del();">删除用户</a> <a href="javascript:void(0);" title="" onclick="frs();">更新用户</a> </div> <div>现有用户: <p id="t"> </p></div> </body></html>