我在一个名为list.js的文件中有一个JSON对象,它看起来像这样 - >
var jsonData = [
{
name: "Friends",
items: [
{
name: "Steve",
job: "pro bowler",
size: "tall",
description: "Steve's my man!"
},
{
name: "Jessica",
job: "HR",
size: "average",
description: "a dear friend"
}
]
},
{
name: "Co-Workers",
items: [
{
name: "Martin",
job: "my boss",
size: "tall",
description: "I don't like him"
},
{
name: "Susan",
job: "Intern",
size: "average",
description: "It's not like I have a crush on her or anything..."
}
]
}
]
我有一个网页,其上的数据看起来像这样 - >
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="list.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title></title>
</head>
<body>
<table>
<tr>
<td>
<table>
<tr><td>Name</td><td class="name">Jenkins</td></tr>
<tr><td>Job</td><td class="job">Accountant</td></tr>
<tr><td>Size</td><td class="size">Small</td></tr>
</table>
</td>
<td class="description">average joe.</td>
<td>
<button class="learn">Learn</button>
</td>
</tr>
</table>
<script type="text/javascript">
$(".learn").click(function(){
var data = {
// captures the information relevent to the button in a key-value array
name: $(this).closest("table").find(".name").text(),
job: $(this).closest("table").find(".job").text(),
size: $(this).closest("table").find(".size").text(),
description: $(this).closest("td").siblings(".description").text()
}
console.log(data);
jsonData[0].items.splice(0, 0, {
name: $(this).closest("table").find(".name").text(),
job: $(this).closest("table").find(".job").text(),
size: $(this).closest("table").find(".size").text(),
description: $(this).closest("td").siblings(".description").text()
});
});
</script>
</body>
</html>
我尝试使用splice()将按钮点击捕获的数据(之后可以在控制台中看到)添加到JSON对象的第一个元素&#34;#34 ;项目&#34;部分。我需要一些帮助来理解我做错了什么,任何建议都会受到赞赏。谢谢。
答案 0 :(得分:0)
纯JavaScript或jQuery无法将数据保存到本地JSON文件。您需要服务器端脚本才能执行此操作。除此之外,您的代码工作正常。