【问题标题】:jQuery - run a function from another pagejQuery - 从另一个页面运行一个函数
【发布时间】:2011-09-12 06:26:48
【问题描述】:

我有一个帐户页面,其中包含使用 .load 加载页面的链接。我想知道如何从另一个页面(而不是从帐户页面)进入加载帐户信息页面?另一个页面只有一个到 account.html 的常规链接,如果已加载,那么我看不到 load-account-information.html 选项卡。我可以以某种方式在 URL 中传递函数 loadAccountInfomration 吗?谢谢!

帐户页面

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

<a href="#" onclick="loadAccountInformation()">My Information</a>

其他页面

<a href="account.html">Account Information</a>

帐户页面上有多个加载功能,我只想知道我是否可以在另一个页面上单击时运行一个。

【问题讨论】:

  • 为什么还需要传递loadAccountInformation 函数?这似乎是一个相当简单的功能。你能简单地在其他页面的 HTML 中包含相同的功能代码吗?
  • @webwrks 你想用相同的功能加载不同的页面吗?我还是没听懂你的问题。
  • 不,我无法在加载时运行它的原因是我在页面上有其他链接。我只想从另一个页面链接到这个特定的链接(以及其他我弄清楚如何做的链接)。
  • 您可以为每个链接编写点击事件查看api.jquery.com/click

标签: jquery


【解决方案1】:

如果您想从另一个页面上的链接在一个页面上运行特定脚本,您可以使用哈希标签。将 #load-account-info 之类的内容附加到 URL 的末尾:

<a href="account.html#load-account-info">Account Information</a>

然后在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 plugin 增加了支持。

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

来源:Working with single page websites and maintaining state using a URL hash and jQueryOn - window.location.hash - Change?

【讨论】:

  • 我现在面临的问题是这是一个菜单链接,如果从菜单中单击它(加载了帐户页面),它不会加载。有没有办法强制它重新加载?
  • 好的,我添加了对它的支持。 showAccountInfo() 函数将在页面加载和哈希更改时调用。
【解决方案2】:

听起来您试图从 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');
        })

    });
}

<a href="#" onclick="loadAccountInformation()">My Information</a>

如果这就是你要找的东西,我建议你用这样的东西进行更多的调制

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);

    })

}

【讨论】:

    【解决方案3】:

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

    如果您想在从另一个页面到达帐户页面后运行该函数,那么您可以在页面加载后调用它。比如……

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

    【讨论】:

    • thx 但这个问题是我只想在特定的点击上运行它,因为我在这个页面上有其他链接并且不能在页面加载时运行它......
    • 好的,如果我认为我理解您想要实现的目标,从某些传入链接有条件地运行该功能,那么 Paperjam 的答案将是您最好的选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    相关资源
    最近更新 更多