仅更改一个<a></a>的背景颜色

时间:2013-08-16 21:24:31

标签: jquery

其实我有这个jquery代码:

$(function() {
  $(".text").click(function() {
   $("#Content").html($(this).next(".text1").html());
   $(this).css( "color", "red" );
   });
 });

我想改变的是,只有最近点击的带有“text”类的a-tag才会将颜色更改为红色。或者更好地说当点击带有类文本的a-tag时,最后点击的a-tag中的红色将被删除!总结:只有一个标签应该同时具有红色!

5 个答案:

答案 0 :(得分:2)

假设a元素是兄弟姐妹,例如:

<a class="demo" href="#">link one</a>
<a class="demo" href="#">link two</a>
<a class="demo" href="#">link three</a>
<a class="demo" href="#">link four</a>

我建议:

$(".demo").click(function () {
    $(this).css('color', 'red').siblings().css('color','');
});

JS Fiddle demo

但是不是直接操纵CSS,而是更容易采用相同的方法并应用/删除特定的类:

$(".demo").click(function () {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});

JS Fiddle demo

如果他们不是兄弟元素,例如:

<ul>
    <li><a class="demo" href="#">link one</a></li>
    <li><a class="demo" href="#">link two</a></li>
    <li><a class="demo" href="#">link three</a></li>
    <li><a class="demo" href="#">link four</a></li>
</ul>

然后我建议:

$(function () {
    $(".demo").click(function () {
        $('a.highlight').removeClass('highlight');
        $(this).addClass('highlight');
    });
});

JS Fiddle demo

参考文献:

答案 1 :(得分:1)

如何将最后点击的链接保留在变量中?

$(function () {
    var lastClicked;
    $(".text").click(function () {
        $("#Content").html($(this).next(".text1").html());
        if (lastClicked != undefined) {
            $(lastClicked).css("color", "");
        }
        lastClicked = this;
        $(this).css("color", "yellow");
    });
});

Check demo here。当然,将颜色从"yellow"更改为"red"(我使用的是黄色,因为它会引起更多关注演示。

答案 2 :(得分:1)

你去了:

$(function() {
  $(".text").click(function() {
   $('.text').css('color','');
   $(this).css( "color", "red" );
   });
 });

http://jsfiddle.net/d7Nyu/

答案 3 :(得分:1)

您可以使用:

$(function () {
    $(".text").click(function () {
        $("#Content").html($(this).next(".text1").html());
        $(".text").css("color", "");
        $(this).css("color", "red");
    });
});

答案 4 :(得分:0)

首先从所有其他节点中删除颜色,请参阅下面的评论......

$(function() {
    $(".text").click(function() {
       $(".text").css("color",""); // remove the color from all other nodes first
       $("#Content").html($(this).next(".text1").html());
       $(this).css( "color", "red" );
     });
 });