我有两页。让我们拨打第一页index.html
和第二页products.html
。
在products.html
上我有一个隐藏的div,除非用户点击按钮显示它,如下所示:
$(document).ready(function() {
$('.product-highlight').hide();
$('a[href$=shoes').click(function() {
$('#shoes').show();
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product">
<img src="http://placehold.it/100x100"/>
<a href="#shoes">Show Shoes</a>
</div>
<div class="product-highlight" id="shoes">
<p>These are the shoes</p>
</div>
&#13;
现在我的index.html
我有一个链接,应直接指向鞋子标签并显示。
到目前为止,我所知道的只是:
$(document).ready(function() {
$('a[href$=shoes]').click(function() {
window.location.href= 'http://sample.com/products.php/';
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#shoes">Take me to the shoes</a>
&#13;
答案 0 :(得分:5)
您可以使用: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';
});
});
答案 1 :(得分:1)
一个策略:
拥有指向http://sample.com/products.php#shoes的index.html链接(普通的<a href="/products.php#shoes">
会做,不需要在这里进行jQuery点击事件。)
让products.php检查'#shoes'的document.location.hash,如果存在则触发$('#shoes').show()
。
答案 2 :(得分:1)
然后在产品页面的javascript中,如果它看到需要的产品,它可以自动触发您应该点击该页面上任何元素的点击事件,以使其显示。
This问题有一个如何使用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];
}
}
}
答案 3 :(得分:1)
在 index.html
中的链接<a href="products.html#shoes">Take me to the shoes</a>
在您的 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');
}
});
如果 products.html 中的location.hash
元素具有#shoes
目标,则该脚本会触发事件按钮'click'
以显示您的太棒了。
答案 4 :(得分:1)
添加一行代码,如下所示:
$(document).ready(function() {
$('.product-highlight').hide();
$('a[href$=shoes').click(function() {
$('#shoes').show();
});
// add this line...
$(window.location.hash).show();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product">
<img src="http://placehold.it/100x100"/>
<a href="#shoes">Show Shoes</a>
</div>
<div class="product-highlight" id="shoes">
<p>These are the shoes</p>
</div>
&#13;