从一个页面调用 javascript 函数以在第二个页面上添加元素

Calling javascript function from one page to add element on second page

本文关键字:第二个 元素 添加 函数 调用 一个 javascript      更新时间:2023-09-26

我正在尝试从一个页面调用javascript函数以在另一个页面中添加元素。该函数正在被调用,但问题是当我将其重定向到新页面时,之后的代码不会执行。

window.func = function() {
location.href = 'second.html';
var div = document.getElementById("div1");
var button = document.createElement("button");
div.appendChild(button);
}

此函数由第一页调用,重定向后的更改应在第二页中进行。我不能对 page2 使用 document.ready 函数,因为我不希望每次加载 page2 时都发生更改,而是我希望仅在按下 page1 中的按钮后进行更改。

您需要通过传递某种标志(即通过 URL 参数)并在加载第二页时检查值是否存在然后执行函数来执行第二页中的代码

因此,

经过多次尝试,我能够实现我想要的。我从一个页面重定向到另一个页面,但我在第二页的 url 中添加了一个字符串。

function myFunction() {
window.location.href = "html2.html?sound";
}

然后在第二页中,仅当 url 包含某个单词时,我才调用该函数。 函数 myFunc2(){

var url = document.URL;
url = url.split('?');
console.log(url[1]);
var temp = url[1];
if(temp == "sound") {
    console.log("sada");
    var button  = document.createElement("button");
    button.innerHTML = "hello";
    document.getElementById("div1").appendChild(button);
 }
}

每次页面加载时都会调用该函数,但仅在 url 包含"声音"字时才添加按钮。