如果元素具有“;被禁用”;班

Intercept and prevent all click events if element has "disabled" class

本文关键字:如果 元素      更新时间:2023-09-26

我真的厌倦了这种模式:

$("#moveButton").click(function() {
    if ($(this).hasClass("disabled")) {
        return;
    }
    //do something
});

我想拦截元素的所有点击事件,这些元素动态添加了类"disabled"

我试过这个:

$('input,a,div').click(function(event){
    if ($(this).hasClass("disabled")) {
        event.preventDefault()
        event.stopPropagation();
    }
});

但不知怎么的,它不起作用。这个脚本在我的页面顶部.js


更新缺点是"disabled"类可以动态添加。

因此,如果您已经向按钮添加了事件侦听器,则必须有一个INTERCEPT所有单击处理程序的解决方案,并检查该元素现在是否已禁用。如果是,请停止此事件以由处理程序捕获。

过滤掉那些元素?

$('input,a,div').not('.disabled').on('click', function(){
    // do stuff 
});

如果稍后添加该类,则可以使用委托的事件处理程序,并且如果您真的想为所有具有该类或在这样一个元素中的元素返回false:

$('input,a,div').on('click', function(e) {
    if ( $(e.target).closest('.disabled').length ) return false;
});

编辑:

如上所述,如果委托了处理程序,您可以过滤掉稍后在事件处理程序中添加的类,例如:

//bind an event handler to all DIV element that does NOT have a .disabled class
$(document).on('click', 'div:not(.disabled)', function() {
    alert('ok');
});
// even if we add the class later, the event handler above will filter it out
$('.test').eq(1).addClass('disabled');

编辑

使用此代码

    $('input,a,div').click(function(event){
    if ($(this).hasClass("disabled")) {
        return false;
    }
});

已解决:

我发现了两种拦截方式:


1) 不是拦截。正如@adeneo所说,当附加事件处理程序时,我们可以将.on(与测试方法一起使用:

$(document).on('click', 'div:not(.disabled)', function() {
    alert('ok');
});

查看他的答案以了解更多详细信息,如果您觉得这很有帮助,请投票支持他的答案。


2) 我们可以将此代码放在顶部,以便首先执行,但请确保在渲染DOM时添加它

$("a,div,input").click(function(event){
    if($(this).hasClass('disabled')){ 
       event.stopImmediatePropagation()
    }
});

这将阻止所有现有的.click.on('click'.live('click'处理程序被执行如果它们没有其他参数

如果您已经有大量的处理程序并且不想重写它,那么这个解决方案是很好的。示例

您可以使用伪类:disabled:

$('input:disabled,a:disabled,div:disabled').click(function() {
    return false;
});