如何禁用自定义复选框的单击事件

How to disable the click event for the customized checkbox

本文关键字:单击 事件 复选框 何禁用 自定义      更新时间:2023-09-26

添加类disabled后,我试图使用jquery禁用自定义复选框。以下是我迄今为止尝试的代码。

$('span').click(function(e){
        $(this).toggleClass('active');
});
$('.disabled').click(function(e){
    e.stopPropagation();
    return false;
});

.CSS

span{
    width: 16px;
    height: 16px;
    display: inline-block;
    cursor: pointer;
    background-color: gray;
}
span.disabled{
    cursor: not-allowed;
}
cite.fa-check{
    font-size: 14px;
    color: #fff;
    margin-left: 1px;
    display: none;
}
span.active cite.fa-check{
    display: inline-block;
}

如果我将类disabled添加到我的复选框中,我的事件应该不起作用。任何帮助将不胜感激。提前谢谢。

工作演示

将代码更新到下面。 jquery not() 选择器避免上述元素上的事件。 您不需要使用 $('.disabled') 单击事件。

查看小提琴的工作演示

$('span').not('.disabled').click(function(e){
    $(this).toggleClass('active');
});

您可以使用hasClass

你只需要这个 js

$('span').click(function(e){
    if($(this).hasClass( "disabled" )==false){
        $(this).toggleClass('active');
    }
});

检查这个小提琴

只需通过检查类是否存在来检查单击的元素是否被禁用或否

$('span').click(function(e){
    if($(this).hasClass("disabled"))
    {
        return false;
    }
    else
    {
        $(this).toggleClass('active');
    }
});

$('.disabled').click(function(e){
    return false;
    e.stopPropagation();
});