标题可能听起来有点令人困惑,因为我不知道如何措辞,但这是我的情况。
假设我有两页。一个是我的主页,另一个是展示页面。
我想要完成的就是这个。当我单击索引页面上的 Showcase 1 链接时,我希望浏览器转到展示页面并自动打开第一个展示。 这可能吗?
主页有一个片段如下:
<a href="#">Showcase 1</a>
<a href="#">All Showcases</a>
展示页面的片段如下:
$(document).ready(function() {
$('.showcases').css('display', 'none');
$('#showcase-link-one').click(function() {
$('#showcase-two').stop(true, true).hide('fast');
$('#showcase-three').stop(true, true).hide('fast');
$('#showcase-one').stop(true, true).show('fast');
});
$('#showcase-link-two').click(function() {
$('#showcase-one').stop(true, true).hide('fast');
$('#showcase-three').stop(true, true).hide('fast');
$('#showcase-two').stop(true, true).show('fast');
});
$('#showcase-link-three').click(function() {
$('#showcase-one').stop(true, true).hide('fast');
$('#showcase-two').stop(true, true).hide('fast');
$('#showcase-three').stop(true, true).show('fast');
});
});
ul {
list-style-type: none;
}
.showcase-link {
text-decoration: none;
}
.showcase-link:hover {
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="showcase-header">
<ul>
<li><a href="#" id="showcase-link-one" class="showcase-link">Showcase One</a></li>
<li><a href="#" id="showcase-link-two" class="showcase-link">Showcase Two</a></li>
<li><a href="#" id="showcase-link-three" class="showcase-link">Showcase Three</a></li>
</ul>
</div>
<div class="showcases" id="showcase-one">
<p>You Clicked on Showcase One</p>
</div>
<div class="showcases" id="showcase-two">
<p>You Clicked on Showcase Two</p>
</div>
<div class="showcases" id="showcase-three">
<p>You Clicked on Showcase Three</p>
</div>
最佳答案
一种方法是在单击该链接时在 URL 中设置哈希值。
<a href="http://example.com/#link-one">Showcase 1</a>
然后使用 JS,您可以使用 window.location.hash
检查哈希并打开右侧的展示柜。
假设您将所有可点击的展示保存在一个数组中
var showcase = ['#link-one', '#link-two', '#link-three'];
$(document).ready(function() {
$('.showcases').css('display', 'none');
$('#showcase-link-one').click(function() {
$('#showcase-two').stop(true, true).hide('fast');
$('#showcase-three').stop(true, true).hide('fast');
$('#showcase-one').stop(true, true).show('fast');
});
$('#showcase-link-two').click(function() {
$('#showcase-one').stop(true, true).hide('fast');
$('#showcase-three').stop(true, true).hide('fast');
$('#showcase-two').stop(true, true).show('fast');
});
$('#showcase-link-three').click(function() {
$('#showcase-one').stop(true, true).hide('fast');
$('#showcase-two').stop(true, true).hide('fast');
$('#showcase-three').stop(true, true).show('fast');
});
if($.inArray(window.location.hash, showcase)) // check to see if it's a showcase
$( '#showcase-' + window.location.hash.replace('#') ).trigger('click')
});
像这样,您可以发送链接中的信息并在下一页上使用它。
关于javascript - 使用 jQuery 元素链接到另一个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27944841/