Jquery - 更改链接的颜色

时间:2013-09-24 19:48:13

标签: jquery

我有以下内容:

     <div id="libdiv" class = "libraryheader ">
         <a href="#"  class="libraryheader" id="videoLink"  /> Videos </a>
         | <a  href="#" class="libraryheader"  id="articleLink" /> Articles </a> 
         | <a href="#" id="newsLink" class="libraryheader"  /> News </a>
     </div> 

当我点击一个链接时,我喜欢我喜欢转换黄金的链接颜色,而其他链接是灰色的。

    .libraryheader
     {

        font-family: sans-serif;
        font-size: 24px;
        color: #4F5A5E;  /* grey color */ 
        text-decoration: none;
     }

    .libraryheaderselected
    {

      font-family: sans-serif;
      font-size: 24px;
      color: gold;
      text-decoration: none;
    }

发生的事情是,当我选择链接时,它们会变成黄金但是当我选择另一个链接时,所选择的仍然是黄金并且不会变为灰色。我只喜欢选择的链接是黄金。所有其他人应默认为灰色。

这是我的代码:

 $('#libdiv a').click(function () {

            $(this).removeClass('libraryheaderselected');
            $('#videoLink').addClass('libraryheader');
            $('#articleLink').addClass('libraryheader');
            $('#newsLink').addClass('libraryheader');

            $(this).addClass('libraryheaderselected');             


        });

5 个答案:

答案 0 :(得分:0)

你试过这个吗?

$('#libdiv a').click(function () {
   $('#libdiv a').removeClass('libraryheaderselected');
   $('#videoLink').addClass('libraryheader');
   $('#articleLink').addClass('libraryheader');
   $('#newsLink').addClass('libraryheader');
   $(this).addClass('libraryheaderselected');  
});

答案 1 :(得分:0)

您可以非常轻松地使用

轻松完成此任务
$('#libdiv a').click(function () {
    // Toggle the two classes on the clicked item. Since all items start with
    // just the class libraryheader, this will remove it and add the selected
    $(this).toggleClass("libraryheader libraryheaderselected")
        // Then go work on the sibling links (i.e. all except the one clicked)
        .siblings("a")
        // and reset them back to "libraryheader" status
        .removeClass("libraryheaderselected").addClass("libraryheader");
});

一旦你这样做,你就可以忘掉它;无论链接的数量或ID如何,它都能正常工作。

答案 2 :(得分:0)

$("#libdiv a").on("click",function(){
  $(this).addClass("libraryheaderselected");
  $(this).siblings().removeClass("libraryheaderselected");
});

这将更有效,因为您不必将每个链接中的类作为单独的函数删除,您可以将其作为2个方法来执行。第一个将类添加到您单击的内容中。第二个从所有兄弟姐妹中删除该类

答案 3 :(得分:0)

以下是一个示例:http://jsbin.com/ebECOR/1/edit

var links = $('#libdiv a');
$('#libdiv').on('click', 'a', function(e) {
  e.preventDefault();
  $(links).removeClass('libraryheaderselected');
  $(this).addClass('libraryheaderselected');
});

答案 4 :(得分:0)

首先,无需在任何链接中添加或删除libraryheader类。 HTML元素一次可以包含多个类。这意味着所有链接都可以保留libraryheader类,而您只需切换指定其文本颜色的辅助类(例如selected)。

所以你需要的就是这个:

$('#libdiv a').click(function () {
    $('#libdiv a.selected').removeClass('selected');
    $(this).addClass('selected');
});

此外,您的CSS是多余的。所有你需要的是:

 .libraryheader
 {

    font-family: sans-serif;
    font-size: 24px;
    color: #4F5A5E;  /* grey color */ 
    text-decoration: none;
 }

.libraryheader.selected
{
    color: gold;
}
相关问题