【发布时间】:2022-01-18 08:16:43
【问题描述】:
我有两个 html 页面,当用户从第一个 html 页面链接单击时,我想检索一个 JSON 对象。当我单击第一页上的第一个链接时,链接有不同的 Id 我想获取第一个信息。问题是我单击的哪个链接,它显示了数据中的所有信息。我需要一种方法来解决它。提前致谢
(1st html page)
<a href="2nd-page.html" id="one">info 1</a> <br><br>
<a href="2nd-page.html" id="two">info 2</a>
const data = [
{
id: "two",
h1: "this is test two",
p: "sum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC",
list: `
<li>dog</li>
<li>fox</li>
<li>cat</li>
`
},
{
id: "one",
h1: "this is a test one",
p: "Contrary to popular belief, Lorem Ipsum is not simply random text.",
list: `
<li>red</li>
<li>Blue</li>
<li>yellow</li>
`
}
]
document.getElementById("heading").innerHTML = `${data.map(function(unit){return unit.h1})}`
document.getElementById("paragraph").innerHTML = `${data.map(function(unit){return unit.p})}`
document.getElementById("list").innerHTML = `${data.map(function(unit){return unit.list})}`
<!-- 2nd html page -->
<!DOCTYPE html>
<html>
<body>
<h2 id="heading"></h2>
<p id="paragraph"></p>
<ul id="list"></ul>
</body>
</html>
【问题讨论】:
-
超链接都指向同一个页面...您希望发生什么?
-
添加URL参数
<a href="2nd-page.html?id=two" id="two">info 2</a>,然后根据URL参数显示数据。 -
第二页就像一个模板,当我点击第一页hpyerlink它应该根据js数据填充第二页元素(h2,p,ul)
-
您如何期望它神奇地知道您之前点击了哪个链接?这就是@Dula 向您展示的内容。向 URL 添加参数,以便您知道要显示哪些数据。
标签: javascript javascript-objects innerhtml getelementbyid template-literals