单击转到页面并执行功能

时间:2010-10-05 21:07:56

标签: jquery events click

我有一个包含多个元素的页面(第A页)。它被设置,所以所有都隐藏但是一个。当您单击链接时,它将隐藏当前显示的链接,并仅显示与您单击的链接对应的部分。我有完美的代码。我还有一个单独的页面(页面B),其中包含一个链接列表。当您单击其中一个链接时,我想加载包含多个元素的页面(页面A),并显示与上一页上单击的链接对应的元素。下面是我现在的代码。它完美地加载页面,但它没有显示相应的元素(我想因为在运行代码时可能该元素不存在,因为页面仍在加载?)。

$(function() {
  $('li').click(function(){ //link that is clicked on
    var currentId = $(this).attr('id'); //capture id of clicked item
    window.location = 'next-page.php'; //load new page
    $('#all-elements').fadeOut(0); //hide all elements
    $('currentId').fadeIn("slow"); //show only corresponding element
    return false;
  });
});

我已将其设置为第一页上的列表项和我想要显示的元素具有相同的ID。我的想法是,我可以捕获当前的id并在函数中使用该值,如上所述。我知道我的问题类似于问题found here,但我不认为#技术会对我正在做的事情起作用。

3 个答案:

答案 0 :(得分:4)

这不起作用,因为window.location之后运行的代码在当前页面上执行,而不是在您尝试加载的页面上执行。

为了获取要加载的页面以执行任何javascript,它必须位于该页面上,而不是当前页面上。修改你的代码,它应该工作:

在第B页上:

$(function() {
  $('li').click(function(){ //link that is clicked on
    var currentId = $(this).attr('id'); //capture id of clicked item
    window.location = 'next-page.php#' + currentId; //load new page
    return false;
  });
});

在第A页上:

$(function() {
  $('#all-elements').hide(); //hide all elements
  $(window.location.hash).fadeIn("slow"); //show only corresponding element
});

答案 1 :(得分:1)

将ID作为参数发送到网址?

window.location ='next-page.php?id ='+ $(this).attr('id');

答案 2 :(得分:-2)

编辑:没关系 - OP包括速记版本,我今天学到了一些东西:

http://api.jquery.com/ready/

- 删除 - 试试这个。这将确保在DOM准备好之前不会调用任何脚本。

$(document).ready(function () {
  $('li').click(function(){ //link that is clicked on
    var currentId = $(this).attr('id'); //capture id of clicked item
    window.location = 'next-page.php'; //load new page
    $('#all-elements').fadeOut(0); //hide all elements
    $('currentId').fadeIn("slow"); //show only corresponding element
    return false;
  });
});