gpt4 book ai didi

javascript - 更改类后jquery继续选择元素

转载 作者:太空宇宙 更新时间:2023-11-03 20:41:39 24 4
gpt4 key购买 nike

我有一个按钮,它必须在满足某些条件后改变它的行为。

所以我按类选择按钮,我想在满足条件时删除该类,并向该元素添加一个新类,然后用它做其他事情。但它不工作。

我只是为我的问题编了一个例子。

这是代码:

$('.button-1').click(function(){
$('.box').width(function(){
return $(this).width() + 10;
});
$(this).removeClass('button-1').addClass('button-2');
});
$('.button-2').click(function(){
$('.box').width(function(){
return $(this).width() - 10;
});
$(this).removeClass('button-2').addClass('button-1');
});

它是 Fiddle

我希望这会在增加和减少黑框宽度之间切换,但它一直在增加。

最佳答案

那是因为事件是静态绑定(bind)在按钮上的,像这样使用事件委托(delegate):

$(document).on('click','.button-1', function(){
$('.box').width(function(){
return $(this).width() + 10;
});
$(this).removeClass('button-1').addClass('button-2');
});
$(document).on('click','.button-2', function(){
$('.box').width(function(){
return $(this).width() - 10;
});
$(this).removeClass('button-2').addClass('button-1');
});

DEMO

关于javascript - 更改类后jquery继续选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25117566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com