如何在点击时更改班级 [英] how to change classes on click

查看:99
本文介绍了如何在点击时更改班级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有结构:

<table style="width: 100%;">
    <tr>
        <td>
            <a href="#" class="yy">one</a>
        </td>

    </tr>
    <tr>
        <td>
            <a href="#" class="xx">Two</a>
        </td>

    </tr>
    <tr>
        <td>
            <a href="#" class="xx">Three</a>
        </td>

    </tr>
</table>

CSS:

.xx {
    border: 5px solid green;    
}

.yy {
    border: 5px solid red;    
}

现在单击<a>时,其类应更改.也就是说,如果它是"xx",那么它应该变成"yy",反之亦然,其余的<a>应该保持原样, 我尝试了类似(ref:如何更改< a> jquery中的标签)

now on click of <a> it's class should get changed. i.e. if it's 'xx' then it should turn 'yy' and vice-versa, and rest of the <a> should remain as it is, I tried something like (ref:how to change class of <a> tags in jquery)

$("a.xx").click(function() {
  $(".yy").not(this).removeClass("yy");
  $(this).toggleClass("yy");
});​

但是它不能那样工作,我试图调整代码,但是不起作用.有人可以帮忙吗.

but it didnt work that way, I tried to tweak the code, but it's not working. Can somebody help.

可能我的问题还不够清楚: 如果我点击第二个<a>/任何其他<a>,那么它应该变成红色并且标签的其余部分应该是绿色的.如果<a>是红色,则它应该变成绿色,其余的应该变成红色,反之亦然.

May b my question was not clear enough: if I click on 2nd <a>/ any other <a> then it should turn red and rest of the tag should be green.i.e. if the <a>is having red color, then it should turn green and and rest of the should be in red, and vice-versa .

编辑以获取更明确的要求(基于sje397的回复): 说我正在单击具有类xx/yy的类,即再次单击它应该更改,即如果xx则应返回到yy,如果您再次单击它,则应返回到xx. –

EDIT for more clear requirement (based on replies from sje397 ): say I am clicking on a having class xx/yy and i.e. I click on it again it should change i.e. if xx then it should go back to yy, if u again click on it, it should go back to xx. –

推荐答案

$("a").click(function() {
  $(this).toggleClass("yy").toggleClass("xx");
});​

编辑(由于作者的评论)

如果您只想拥有一个突出显示的标签(即类别为"yy"),而所有其他类别的类别都为"xx",则可以执行以下操作:

If you want to have only one highlighted tag (i.e. having the class 'yy') and all others having the class 'xx', you can do:

$("a").click(function() {
  var $this = $(this); // this is just for performance
  if(!$this.hasClass('yy'))
    $('.yy').toggleClass("yy").toggleClass("xx");
  $this.toggleClass("yy").toggleClass("xx");
});​

但是,通常,您将使用css的'cascading'属性来简化操作.例如,不必切换类,而只需向所选元素添加一个附加类即可.然后组织CSS,以便在这种更具体的情况下,您要突出显示的显示属性被覆盖.例如,使用以下CSS:

Usually, however, you would use the 'cascading' property of css to simplify things. For example, rather than switching classes, just add an additional class to the selected element. Then organise your CSS so that in this more specific case, the display properties which you want for the highlight override. For example, with this CSS:

.xx {
    border: 5px solid green;    
}

.xx.yy {
    border: 5px solid red;    
}

您只需要添加和删除'yy'类,而不必理会'xx'类.

You just need to add and remove the 'yy' class and leave the 'xx' class alone.

这篇关于如何在点击时更改班级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆