gpt4 book ai didi

jQuery - 检查类是否存在,如果不破坏函数

转载 作者:行者123 更新时间:2023-12-01 06:35:19 24 4
gpt4 key购买 nike

我试图根据 CSS 类的存在来销毁一个函数。

我想检查类.active,该类通过单击按钮进行切换。我尝试使用

if(jQuery(#test).hasClass('.active')

但它只能工作一次,如果我删除 .active ,该函数仍然在运行,而我想在删除 .active 类后销毁它。

我也尝试了.unbind()但没有用。

请告诉我如何在删除 .active 类后完全销毁此功能

    function destroy_no_active_class(){
jQuery('#test.active').mouseover(function (e) {
e.stopPropagation();e.preventDefault();
jQuery(this).addClass('highlight');
}).mouseout(function () {
jQuery(this).removeClass('highlight');
}).click(function(e){
e.stopPropagation();
e.preventDefault();
show_data(this);
});

});
}

最佳答案

假设“销毁函数”只是意味着您希望它停止突出显示该元素,您可以简单地在处理程序被触发后进行检查,并有条件地执行逻辑。这也比解除绑定(bind)处理程序更有用,因为如果元素再次变为“事件”,它将自动再次工作。

function destroy_no_active_class(){
jQuery('#test').on('mouseover.mine mouseout.mine', function (e) {
if ($(this).is(".active")) {
e.stopPropagation();
e.preventDefault();
jQuery(this).toggleClass('highlight');
}
}).on('click.mine', function(e){
if ($(this).is(".active")) {
e.stopPropagation();
e.preventDefault();
show_data(this);
}
});
});
}

在处理程序中,您也可以这样做

if (!$(this).is(".active")) {
$(this).off('mouseover.mine mouseout.mine click.mine');
}

这里的缺点是,如果元素再次变为事件状态,则必须重新绑定(bind)处理程序。 (注意 $ 只是 jQuery 的别名。如果存在命名冲突,只需将 jQuery 替换为 $ > 在上面的代码中,正如您所做的那样。)

关于jQuery - 检查类是否存在,如果不破坏函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17825164/

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