jQuery jquery点击更改类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6065140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery click change class
提问by cj333
I am studying jquery, I want make a effection as: first click, slider down the div#ccc and change the link class to 'aaa'; click again, slider up the div#ccc and change the link class back to 'bbb'. now slider down can work, but removeClass, addClass not work. how to modify so that two effection work perfect? thanks.
我正在学习 jquery,我想产生一个效果:首先单击,向下滑动 div#ccc 并将链接类更改为“aaa”;再次单击,向上滑动 div#ccc 并将链接类更改回“bbb”。现在滑块向下可以工作,但 removeClass、addClass 不起作用。如何修改使两个效果完美运行?谢谢。
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$("#click").click(function() {
$("#ccc").slideDown('fast').show();
$(this).removeClass('bbb').addClass('aaa');
});
$("#click").click(function() {
$("#ccc").slideDown('fast').hide();
$(this).removeClass('aaa').addClass('bbb');
});
});
</script>
<style>
#ccc{display:none;}
</style>
<div id="click" class="bbb">click</div>
<div id="ccc">hello world</div>
采纳答案by Tim Hobbs
回答by SickHippie
Use toggle instead of show/hide and toggleClass instead of add/remove, and merge into a single click event. Something like this (untested and probably doesn't work):
使用toggle 代替show/hide 和toggleClass 代替add/remove,并合并为一个单击事件。像这样的东西(未经测试,可能不起作用):
$("#click").click(function() {
$("#ccc").toggle().animate();
$(this).toggleClass('bbb aaa');
});
回答by Andrew
You are looking for the toggle event, it appears.
您正在寻找切换事件,它出现了。
$(document).ready(function () {
$('div#click').toggle(
function () {
$('div#ccc').slideDown('fast').show();
$('div#click').removeClass('bbb').addClass('aaa');
},
function () {
$('div#ccc').slideDown('fast').hide();
$('div#click').removeClass('aaa').addClass('bbb');
});
});