如何在加载超链接页面后响应事件?

时间:2015-03-21 11:03:41

标签: javascript html hyperlink

我想在客户端点击超链接并加载超链接后是否可以响应事件?哪个事件可以使用超链接中的属性(即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?

1 个答案:

答案 0 :(得分:1)

您可以使用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>

注意:由于此代码在客户端运行,因此用户可能会对其进行更改,因此您必须注意如何继续执行&#34;已保存的&#34;功能,或者您可能会发现自己遇到安全问题。