JQuery show hide div链接

问题描述:

我有一个切换div是众多其中之一,我需要在div打开时将div切换为一种颜色的链接,并且当页面上的另一个链接返回到默认颜色时被点击。 这里是我用来切换div的代码,它的工作原理非常完美!当我添加普通的css代码时,链接在单击另一个链接时保持着色为访问链接。JQuery show hide div链接

function showonlyone(thechosenone) { 
    $('.newboxes').each(function (index) { 
     if ($(this).attr("id") == thechosenone) { 
      $(this).show(200); 
     } else { 
      $(this).hide(600); 
     } 
    }); 
} 

我如何可以添加到这个代码块中选择时,颜色设置为diferent颜色改回当选择另一个链接的默认颜色...谢谢!

+0

你能提供一些HTML代码示例,以显示您的确切标记?你可以创建一个[jsfiddle](http://www.jsfiddle.net) – SirDerpington 2013-04-29 20:27:22

最简单的(在我看来)方法是使用.addClass().removeClass()来申请或删除一个班级。然后,您可以使用CSS来设置颜色和任何其他设置的格式。

function showonlyone(thechosenone) { 
    $('.newboxes').each(function (index) { 
     if ($(this).attr("id") == thechosenone) { 
      $(this).addClass("highlight"); 
     } else { 
      $(this).removeClass("highlight"); 
     } 
    }); 
} 

而在你的CSS后:

.highlight a { /* may need to format differently depending on your HTML structure */ 
    color: #ff0000; /* red */ 
} 

您还可以简化您的代码如下所示:

function showonlyone(thechosenone) { 
    $('.newboxes.highlight').removeClass("highlight"); // Remove highlight class from all `.newboxes`. 
    $('#' + thechosenone).addClass("highlight"); // Add class to just the chosen one 
} 

此代码将等待DOM加载,然后应用“高亮“级首次亮相<div class="newboxes">

$(document).ready(function(){ 
    $(".newboxes:first").addClass("highlight"); 
    // The :first selector finds just the first object 
    // This would also work: $(".newboxes").eq(0).addClass("highlight"); 
    // And so would this: $(".newboxes:eq(0)").addClass("highlight"); 
    // eq(n) selects the n'th matching occurrence, beginning from zero 
}) 
+0

这正是我即将发布的内容,你击败了我! +1 – SamHuckaby 2013-04-29 20:34:45

+0

非常棒!谢谢!一个小东西我怎么能设置一个潜水运行这是默认的div? – 2013-04-30 13:33:17

+0

@WebsterAlexanderIII你的意思是默认?什么功能将与默认的div相关联?你可以简单地在HTML中加入'class =“highlight”',或者'class =“default”',然后按照这种方式操作,例如'$(“。newboxes.default”)。addClass(“highlight”)。 show()' – 2013-04-30 16:18:56

function showonlyone(thechosenone) { 
    $('.newboxes').hide(600).css('color', 'blue').find('#' + thechosenone).show(200).css('color', 'red'); 
} 

假设:此类“newboxes”包含由函数中指定的“thechosenone”指定的元素。

基于CSS的类版本:

function showonlyone(thechosenone) { 
    $('.newboxes').hide(600).removeClass('linkHilightColor').find('#' + thechosenone).show(200).addClass('linkHilightColor'); 
}