交换css类 [英] Swap css class
问题描述
我想使用jQuery在两个链接中交换类。我有一个HTML代码,如:
I would like to swap classes in two links using jQuery. I got a HTML code like:
<div class="showHide1">
<a id="aaa" class="show">AAA</a>
<a id="bbb" class="hide">BBB</a>
</div>
<div class="showHide2">
<a id="aaa" class="show">AAA</a>
<a id="bbb" class="hide">BBB</a>
</div>
和一个简单的.css文件:
and a simple .css file :
.show {
display: block;
}
.hide {
display: none;
}
现在我想在showHide div。
Now I want to swap classes in both links after clicking somewhere on the "showHide" div.
$('#showHide1').click(function() {
if ($("#aaa").hasClass('show')) {
$("#aaa").attr("class","hide");
}
else {
$("#aaa").attr("class","show");
}
if ($("#bbb").hasClass('hide')) {
$("#bbb").attr("class","show");
}
else {
$("#bbb").attr("class","hide");
} `
我相信有更好的方法解决这个问题,因为这只适用于showHide1div,我必须复制几乎相同的代码,以获得它为一个showHide2div。任何人可以给我一个更好的解决方案?
I'm sure there is a better way to solve this problem, because this only works for "showHide1" div, and I have to copy almost the same code to get it working for a "showHide2" div. Could anyone show me a better solution?
感谢
Dawid
推荐答案
扩展cdeszaq的答案,而不是 .show
和 .hide
只使用 .hide
,然后您可以使用以下内容:
To expand of cdeszaq's answer, instead of having .show
and .hide
only use .hide
then you can use the following:
HTML:
<div id="showHide1" class="showHide">
<a id="aaa">AAA</a>
<a id="bbb" class="hide">BBB</a>
</div>
<div id="showHide2" class="showHide">
<a id="aaa">AAA</a>
<a id="bbb" class="hide">BBB</a>
</div>
CSS:
.hide {
display: none;
}
JS:
$('.showHide').click(function() {
$('a', this).toggleClass('hide'); //I had inverted my selector and context earlier, this is correct
});
这篇关于交换css类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!