[英]So I have two html files and they are both linked to another another and share the same css/js file
So I have two html files and they are both linked to another another and share the same css/js file.所以我有两个 html 文件,它们都相互链接并共享相同的 css/js 文件。 when I use a btn on one index.html and click it I want it to return append something to a section/div on index2.html.
当我在一个 index.html 上使用 btn 并单击它时,我希望它返回 append 某些内容到 index2.html 上的一个部分/div。 I have the code but for some reason when I run it I get an error so I console.logged it and it returns null. How do I access elements from another html file do I need to import that into js?
我有代码,但出于某种原因,当我运行它时出现错误,所以我对它进行了控制台记录并返回了 null。如何访问另一个 html 文件中的元素是否需要将其导入 js? index:
指数:
<a href="index.html">home</a>
<a href="test.html">test</a>
<button class="btn" onclick="add()">addP</button>
index2:索引 2:
<a href="index.html">home</a>
<a href="test.html">test</a>
<h1>add p below </h1>
<div class="pbox">
</div>
I want to access the div.pbox我想访问 div.pbox
You are facing a few issues here.您在这里面临一些问题。 On the home page there is no
pbox
and on the test page there is no add button
this is easy enough to solve with a conditional to see if they even exist or using 2 JavaScript files.在主页上没有
pbox
,在测试页面上也没有add button
,这很容易解决,条件是查看它们是否存在或使用 2 JavaScript 文件。
The next problem you face is how you store the information and get it from one page to another.您面临的下一个问题是如何存储信息并将其从一个页面获取到另一个页面。 Once the page reloads the information will just go away.
页面重新加载后,信息将消失 go。 The answer in this case would be local storage.
在这种情况下,答案是本地存储。
When the page loads it checks for the existence of a list in local storage.当页面加载时,它会检查本地存储中是否存在列表。 If it exists it gets that information and parses it.
如果它存在,它会获取该信息并对其进行解析。 If it does not exist it is just an empty array.
如果它不存在,它只是一个空数组。 This happens on both pages because they both need this information.
这在两个页面上都会发生,因为它们都需要此信息。
When the test page loads it simply grabs the information in the list and maps over it to fill out the pbox
with whatever is in the list at that time.当测试页面加载时,它只是获取列表中的信息并映射到它上面,以使用当时列表中的任何内容填充
pbox
。
On the home page once the button is clicked it pushes the new item to the list array then updates the local storage.单击主页上的按钮后,它会将新项目推送到列表数组,然后更新本地存储。
Here is the Sandbox Link这是沙盒链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.