[英]How do I make a JS function triggered in one HTML page edit elements defined in a second HTML page?
Basically I have two HTML pages, and both are connected to the same JS file.基本上我有两个 HTML 页面,并且都连接到同一个 JS 文件。 I want a function triggered by an event handler element in the first HTML to edit an element in the second HTML page, and then open it.
我想要一个由第一个 HTML 中的事件处理程序元素触发的 function 来编辑第二个 HTML 页面中的元素,然后打开它。
Here's a very basic example:这是一个非常基本的示例:
$("#p1").click(function() { $("#p2el").text("TEST"); })
<button id="p1">CLICK</button>
In this example, the button p1
is defined in the first HTML, and the p2el
element is defined in a second HTML page, both linked to the same JS file.在此示例中,按钮
p1
定义在第一个 HTML 中, p2el
元素定义在第二个 HTML 页面中,两者都链接到同一个 JS 文件。
In the above example, I also used location.href
inside the function.在上面的例子中,我还在 function 中使用了
location.href
。 The idea being that, the element is edited, and automatically the second HTML page is loaded.想法是,元素被编辑,并自动加载第二个 HTML 页面。
It's not working, and I don't know why.它不起作用,我不知道为什么。 The second HTML page loads, but the element
p2el
is not edited.第二个 HTML 页面加载,但元素
p2el
未编辑。
I suspect this is has to do with data not transferring to the second HTML, but I am not sure why and what is happening exactly.我怀疑这与未传输到第二个 HTML 的数据有关,但我不确定为什么以及到底发生了什么。 I tried using
localStorage
inside the function, and then use the stored data as a condition that edits the element in the second HTML page...我尝试在 function 中使用
localStorage
,然后使用存储的数据作为编辑第二个 HTML 页面中元素的条件...
function second() { if(localStorage["key"] == "on") { $("#p2el").text("TEST"); location.href = "secondpage.html" } } $("#p1").click(function() { localStorage["key"] = "on"; second() })
... but It didn't work. ......但它没有工作。
I hope somebody can help me out.我希望有人可以帮助我。
Navigating to a new page completely resets the "JavaScript envirionment".导航到新页面会完全重置“JavaScript 环境”。
Your JS files are reloaded, everything starts anew.你的 JS 文件被重新加载,一切重新开始。 Some things persist through page loads, such as local storage and cookies, but function calls certainly don't.
有些事情会通过页面加载持续存在,例如本地存储和 cookies,但 function 调用肯定不会。
To do what you want to do, you'll need to:要做你想做的事,你需要:
This will probably do the trick for you:这可能会为您解决问题:
if(localStorage["key"] === true) {
localStorage["key"] = false; // reset the key.
$("#p2el").text("TEST");
}
$("#p1").click(function() {
localStorage["key"] = true;
location.href = "secondpage.html"
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.