点击,导航到另一个页面,打开一个由javascript隐藏的div

我有两页。 让我们调用第一页index.html和第二页products.html

products.html我有一个隐藏的div,除非用户单击一个按钮来显示它,如下所示:

为products.html

 $(document).ready(function() { $('.product-highlight').hide(); $('a[href$=shoes').click(function() { $('#shoes').show(); }); }); 
   

These are the shoes

现在在我的index.html我有一个链接应该直接导致鞋子标签并显示它。

到目前为止,我所知道的是:

的index.html

 $(document).ready(function() { $('a[href$=shoes]').click(function() { window.location.href= 'http://sample.com/products.php/'; }); }); 
  Take me to the shoes 

您可以使用:target伪类。 为此定义下一个CSS规则:

 #shoes { display: none; /* hide by default */ } #shoes:target, /* and show either if class show is present (on click) */ #shoes.show { /* or location hash matches id "shoes" */ display: block; } 

在JS中你会添加类show

 $(document).ready(function() { $('.product-highlight').hide(); $('a[href$=shoes').click(function() { $('#shoes').addClass('show'); }); }); 

从索引页面重定向时,您还需要设置哈希#shoes

 $(document).ready(function() { $('a[href$=shoes]').click(function() { window.location.href= 'http://sample.com/products.php/#shoes'; }); }); 

jQuery的.click()没有任何参数,触发该元素上的click事件,因此在最简单的解决方案中,如果用户通过单击shoes链接进入产品页面,则在末尾添加查询字符串(/ products。 PHP / q =鞋)

然后在产品页面的javascript中,如果它看到需要的产品,它可以自动触发您应该点击该页面上任何元素的点击事件以使其显示。

这个问题有一个如何使用jQuery从URL中提取参数的示例。

 function getUrlParameter(sParam) { var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == sParam) { return sParameterName[1]; } } } 

阅读位置哈希

index.html中的链接

 Take me to the shoes 

在您的products.html脚本中:

 $(document).ready(function() { $('.product-highlight').hide(); $('a[href$=shoes]').click(function() { $('#shoes').show(); }); if ( location.hash != 0 && location.hash == '#shoes' ){ $('a[href$=shoes]').trigger('click'); } }); 

当你的#shoes中有一个名为#shoes的元素的location.hash目标时,该脚本将触发事件按钮'click'以显示你的精彩鞋子。

一个策略:

  • 有index.html链接到http://sample.comhttps://stackoverflow.com/products.php (一个普通的会这样做,这里不需要jQuery点击事件。)

  • 让products.php检查document.location.hash为’#shoes’并触发$('#shoes').show()如果存在。

添加一行代码,如下所示:

 $(document).ready(function() { $('.product-highlight').hide(); $('a[href$=shoes').click(function() { $('#shoes').show(); }); // add this line... $(window.location.hash).show(); }); 
   

These are the shoes