加载超链接页面后如何响应事件?
How to respond to an event after loading a hyperlink page?
请问是否可以在客户端点击超链接加载超链接后响应事件?哪个事件可以使用超链接中的属性(即 id、class...等)?
例如,page_A有一个超链接
<a href="page_B" onclick="some_func">link</a>
但是由于 some_func 需要使用 page_B 中的一些属性,假设 page_B 有这一行
<p id="a">hello world</p>
和some_func想用它做点什么(例如document.getElementById("a")
),我怎样才能先加载超链接(page_B)然后运行 some_func?
您可以使用 localStorage 保存您要在第二页上执行的函数的名称,并在加载后调用它。
代码应该是这样的:
JS
// a sample function to be called
function myFunc() {
alert("Called from previous page!");
}
// save the name of the function in the local storage
function saveForLater(func) {
localStorage.setItem("func", func);
}
// if the function exists
if (localStorage.func) {
// call it (not using the evil eval)
window[localStorage.func]();
// remove it from the storage so the next page doesn't execute it
localStorage.removeItem("func");
}
HTML(仅供测试)
<a href="test2.html" onclick="saveForLater('myFunc')">Go to Page 2</a><br/>
<a href="test2.html">Go to Page 2 (not saving function)</a>
注意:由于此代码在客户端运行,因此可能会被用户更改,因此您必须小心如何继续执行 "saved" 函数,否则您可能会发现自己有安全问题。
请问是否可以在客户端点击超链接加载超链接后响应事件?哪个事件可以使用超链接中的属性(即 id、class...等)?
例如,page_A有一个超链接
<a href="page_B" onclick="some_func">link</a>
但是由于 some_func 需要使用 page_B 中的一些属性,假设 page_B 有这一行
<p id="a">hello world</p>
和some_func想用它做点什么(例如document.getElementById("a")
),我怎样才能先加载超链接(page_B)然后运行 some_func?
您可以使用 localStorage 保存您要在第二页上执行的函数的名称,并在加载后调用它。
代码应该是这样的:
JS
// a sample function to be called
function myFunc() {
alert("Called from previous page!");
}
// save the name of the function in the local storage
function saveForLater(func) {
localStorage.setItem("func", func);
}
// if the function exists
if (localStorage.func) {
// call it (not using the evil eval)
window[localStorage.func]();
// remove it from the storage so the next page doesn't execute it
localStorage.removeItem("func");
}
HTML(仅供测试)
<a href="test2.html" onclick="saveForLater('myFunc')">Go to Page 2</a><br/>
<a href="test2.html">Go to Page 2 (not saving function)</a>
注意:由于此代码在客户端运行,因此可能会被用户更改,因此您必须小心如何继续执行 "saved" 函数,否则您可能会发现自己有安全问题。