我有 2 个页面,每个页面都有一个单独的 js 文件。我想创建一个新的 js,就像将这两个页面连接在一起的链接。
在一页上,我显示数组列表中的对象:
html:
<div id="pop-up" class="hidden">
<img src="https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-1100x628.jpg" alt="pop">
</div>
<input id="search" type="text" placeholder="Search..">
<div id="animallist"></div>
JavaScript:
const animals = [{
name: "Cat",
useful: "no",
image: "https://icatcare.org/app/uploads/2018/07/Thinking-of-getting-a-cat.png"
},
{
name: "Dog",
useful: "yes",
image: "https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-1100x628.jpg"
},
{
name: "Fish",
useful: "no",
image: "https://cdn0.wideopenpets.com/wp-content/uploads/2019/10/Fish-Names-770x405.png"
},
]
animals.forEach(addLink);
function addLink(animal, i) {
const div = document.createElement('div');
const animalList = document.createElement('h2');
const image = document.createElement('img');
image.id = "image";
animalList.innerHTML = animal.name + " " +"-"+"useful?" + " "+ animal.useful;
animalList.style.cssText = "text-align:center;"
image.classList.add("highlight");
image.src = animal.image;
div.appendChild(image);
div.appendChild(animalList);
div.dataset.animalName = animal.name;
animallist.appendChild(div);
}
第一页中的一些信息与第二页上的信息相关。我想创建一个通过单击 animal.name
触发的函数,它会将我重定向到第二页并将 animal.name
放入搜索框中,如下所示输入值。问题是,我不确定是否可以从分配给第一页的 js 文件传输一些信息并传输到新的 js 文件(例如动物的索引值),然后将其传递给第二页。
这是jsfiddle ,只是为了实验,我们可以假设这两个页面是相同的,并且我想重定向到不同的 url,但页面看起来相同,并且输入值将更改为 animal.name
?
最佳答案
无法在客户端 JavaScript 上创建文件,但您可以使用 URL 中的变量将用户重定向到第二页
location.replace('/second-page?animal=Aminal&&index=0')
在第二页上,您可以使用以下代码提取这些变量:
function getUrlParams(search) {
const hashes = search.slice(search.indexOf('?') + 1).split('&')
const params = {}
hashes.map(hash => {
const [key, val] = hash.split('=')
params[key] = decodeURIComponent(val)
})
return params
}
console.log(getUrlParams(window.location.search))
// return a object { animal: 'Aminal', index: 0 }
关于javascript - 创建新的js文件并从其他js文件中获取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60936055/