[英]change class of element, on each mouse click
I want to change class of element, everytime I click on it. 每次点击它我想改变元素类。
on css section I have: 在css部分,我有:
myButton.btn_first_look {
/* some atributes */
}
myButton.btn_second_look{
/* some atributes */
}
little jquery: 小jquery:
$(document).ready(function(){
$('#myButton').click(function() {
$(this).toggleClass('btn_first_look');
$(this).toggleClass('btn_second_look');
})};
So, when I click on element, I expect jquery script to change element class from btn_first_look
to btn_second_look
and otherwise. 所以,当我点击元素时,我希望jquery脚本将元素类从btn_first_look
更改为btn_second_look
,否则。
But boom. 但繁荣。 Nothing happend 什么都没发生
Use removeClass()
and addClass()
respectively 分别使用removeClass()
和addClass()
$('#myButton').click(function() {
//if button has class btn_first_look
if($(this).hasClass('btn_first_look')){
$(this).removeClass('btn_first_look');
$(this).addClass('btn_second_look');
}
//if button has class btn_second_look
else if($(this).hasClass('btn_second_look')){
$(this).removeClass('btn_second_look');
$(this).addClass('btn_first_look');
}
});
This adds whichever class the button doesn't have, and removes the class it does. 这会添加按钮没有的类,并删除它所执行的类。
toggleClass
will take care of add and remove by itself toggleClass
将toggleClass
处理添加和删除
$('#myButton').click(function() {
$(this).toggleClass('btn_second_look btn_first_look');
};
Try this. 尝试这个。
If your element has class btn_first_look
from the start, you can write 如果你的元素从一开始就有类btn_first_look
,你可以写
$(element).toggleClass("btn_first_look btn_second_look");
This will remove class btn_first_look
and add class btn_second_look
. 这将删除类btn_first_look
并添加类btn_second_look
。 If you do that again, it will remove class btn_second_look
and reinstate class btn_first_look
. 如果再次执行此操作,它将删除类btn_second_look
并恢复类btn_first_look
。
Add a parenthesis at the very end. 最后添加一个括号。 Your first (function()
has no close, so it won't work. 你的第一个(function()
没有关闭,所以它不起作用。
That will work for you 这对你有用
$(document).ready(function(){
$('#myButton').click(function(){
$(this).toggleClass('btn_first_look btn_second_look');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.