[英].removeClass doesn't work how addClass does?
Forgive me for being a noob, but shouldn't this work? 请原谅我是一个菜鸟,但不应该这样做吗?
$(document).ready(function() {
$('.button').click(function() {
$(this).addClass('button-clicked');
});
$('.button-clicked').click(function() {
$(this).removeClass('button-clicked');
});
});
Shouldn't the second click remove the class and take it back to .button? 不应该第二次单击删除该类并将其恢复为.button?
Here it is on jsfiddle: http://jsfiddle.net/pXdwM/ 这里是jsfiddle: http : //jsfiddle.net/pXdwM/
no, because at the point you're calling the second click()
the button doesn't have ".button-clicked" and therefore event handler is not assigned. 不,因为在您调用第二次
click()
该按钮没有“.button-clicked”,因此未分配事件处理程序。 You could rewrite it like this 你可以像这样重写它
$('.button').click(function() {
$(this).toggleClass('button-clicked');
});
or use live()
或使用
live()
$('.button-clicked').live("click", function() {
$(this).removeClass('button-clicked');
});
You are adding an event to each element with class '.button-clicked', but the class does not apply until you actually click. 您正在使用类'.button-clicked'向每个元素添加一个事件,但在您实际单击之前该类不适用。 So you need to move the second listener into the first callback, or use the
toggleClass
function: 因此,您需要将第二个侦听器移动到第一个回调中,或者使用
toggleClass
函数:
$('.button').click(function() {
$(this).toggleClass('button-clicked');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.