jQuery – 从另一个页面运行一个函数

我有一个帐户页面,其中包含使用.load加载页面的链接。 我想知道如何从另一个页面(而不是从帐户页面)访问加载帐户信息页面? 另一个页面只有一个到https://stackoverflow.com/questions/7381160/jquery-run-a-function-from-another-page/account.html的常规链接,如果已加载,那么我没有看到load-account-information.html选项卡。 我可以以某种方式在URL中传递函数loadAccountInfomration吗? 谢谢!

帐户页面

function loadAccountInformation() { $('#accountMain').load("load-account-information.html"); } My Information 

其他页面

 Account Information 

帐户页面上有多个加载function,我只想知道是否可以在另一个页面的点击中特别运行一个。

如果要在另一个页面上的链接上运行特定脚本,可以使用哈希标记。 将#load-account-info到URL的末尾:

 Account Information 

然后在account.html上检查它:

 $(function() { // show account info if #showAccountInfo is present showAccountInfo(); // detect url hash changes and fire off showAccountInfo $(window).bind("hashchange", showAccountInfo()); }); function showAccountInfo() { if (window.location.hash == "load-account-info") loadAccountInformation(); } 

注意:并非所有浏览器都支持“hashchange”事件。 因此,有一个jQuery 插件可以增加支持。

编辑 :添加了对检测同一页面上的点击的支持。

来源: 使用单页网站并使用URL哈希和jQuery维护状态 , On – window.location.hash – 更改?

听起来你试图从ajax插入的内容运行ajax调用。

在jquery中使用ajax的很酷的事情是回调。 加上它超级好用。

 function loadAccountInformation() { $('#accountMain').load("load-account-information.html", function () { var ele = $(this); ele.find('a').bind('click', function(){ ele.load('url'); }) }); } My Information 

如果这就是你想要的东西,那么我建议你用这样的东西来模拟一点

 function loadInfo(url){ $('#accountMain').load(url, function () { attachEvents(); } ) } function attachEvents(){ //Add In selector or selectors that can target ajax links $('#linkArea').find('a').unbind('click').bind('click' function(){ var url = this.href; loadInfo(url); }) } 

JavaScript在浏览器中运行,因此您无法远程调用它。 您需要访问“其他页面”上的相同脚本,并将loadAccountInformation函数作为点击处理程序添加到链接中,方法与在帐户页面上执行的操作相同。

如果您想在从其他页面到达帐户页面后运行该function,则可以在页面加载后调用该function。 就像是…

 $(function () { loadAccountInformation(); });