在我的页面上,我放了两个div:nav和内容。 在“nav”里面,我有10个链接。每个人都称为“link1”,“link2”,.... 在“内容”里面,我有10个竞赛div。每一个叫做ilke“divarea1”,“divarea2”,.... 当我点击链接时,新内容将淡出。 我的jquery代码就像:
$("#link1").click(function(){
$("#divarea0,#divarea2,#divarea3,#divarea4,#divarea5,#divarea6,#divarea7,#divarea8,#divarea9,#divarea10").hide();
$("#divarea1").fadeIn(3000);
});
$("#link2").click(function(){
$("#divarea0,#divarea1,#divarea3,#divarea4,#divarea5,#divarea6,#divarea7,#divarea8,#divarea9,#divarea10").hide();
$("#divarea2").fadeIn("fast");
});
这种方式有效。但我知道这是一种愚蠢的方式。有人可以告诉我如何以简单的方式做到这一点? THX
答案 0 :(得分:2)
我看到了一些我们可以做的事情。我们可以使用jQuery的.data()
功能并指定链接的两个“动态”部分:要显示的内容区域以及要显示的速度。从那里,我们绑定并从每个链接中提取这些值。例如:
<div id="nav">
<a href="#" data-area="1" data-speed="3000">Link 1</a>
<a href="#" data-area="2" data-speed="fast">Link 2</a>
...
</div>
$(function(){
// locate and iterate over all the links in the nav container
$('#nav a').each(function(i,e){
// use the "data-area" to determine the content to display
var area = $(e).data('area');
// use the "data-speed" to determine how fast the content should be shown/hidden
var speed = $(e).data('speed');
// bind the click event
$(e).click(function(e){
// use a selector to find divs that match the prefix "divarea"
$('div[id^=divarea]').hide();
// now show the correct content using the two data fields we got earlier
$('#divarea' + area).fadeIn(speed);
});
});
});
<强> Demo 强>
-
如果您想保留链接ID,可以使用以下方法。锚点仍必须包含data-speed
,但您可以保留ID linkN
(其中N
是数字):
$(function(){
$('#nav a').each(function(i,e){
var area = $(e).attr('id').match(/(\d+)$/);
var speed = $(e).data('speed');
$(e).click(function(e){
$('div[id^=divarea]').hide();
$('#divarea' + area).fadeIn(speed);
});
});
});
<强> Demo 强>
答案 1 :(得分:0)
$('#nav a').click(function(){
var idlink = $(this).attr('id').substr(4,2);
$('#contents div').hide();
$('#divarea"+idlink).fadeIn();
}
首先,您在#nav div中的所有链接上收听click事件。然后,在单击时,您将获得id属性并减去您不需要的所有字符,只获取链接的“索引”。 你可以使用之前有两行的索引隐藏#contents中的所有div并使用你想要的所有#divarea淡化。
我不确定这是最好的方式,但它更好,它应该工作! :)
答案 2 :(得分:0)
我建议像: 添加类“链接”或任何你想要的每个链接和一个名为“link_5”的ID,下划线后面的数字与你想要显示的div相关。因此,您还必须在“内容”包装器中为所有div添加一个类“nav”,其中id为“nav_5”,数字对应于appropritate链接。然后:
$(".link").click(function(){
var id = $(this).split('_')[1]; //You get the id value after the underscore
$('.nav').hide(); // You hide all div with the class "nav"
$('#nav_'+id).fadeIn(3000); // You display the div with the id "nav_[id]"
});
正如你完全理解的那样,.link类是一种只用一个jquery请求获取所有链接的方法。如果单击该链接,则拆分id值以获取相应内容div的正确ID。这是任何浏览器上的有效方式,如果您想使用W3C验证您的网站,您不会收到任何“DOM”错误。希望它有所帮助