如何禁用和启用没有特定处理程序名称的单击事件

how to disable and enable click event with no specific handler name

本文关键字:程序 事件 单击 处理 何禁用 启用      更新时间:2023-09-26

我的应用程序中有很多链接,我需要启用/禁用它们的点击事件,但仍然希望允许悬停和其他事件。

所以我需要一种方法(CSS/JS/jQuery)禁用Click事件。 而且也不需要使用处理程序名称。例如:

.HTML:

<a href="#" onclick="runAll()" id="runAll">Run All</a>

JS - 调用禁用函数:

disableElement('#runAll', "no sensors to record"); // call to the disable function

JS - 启用/禁用功能

//disable element (add disable class and unbind from click event)
function disableElement(element, tooltip) {
    $(element).addClass('ui-disabled');
    $(element).disableClick; // need this option!
    if (typeof tooltip != 'undefined' && tooltip != "")
        loadTooltip(element, tooltip);
}
//enable element (remove disable class and bind to click eventl
function enableElement(element) {
    $(element).removeClass('ui-disabled');
    $(element).prop("title", "");
    $(element).enableClick; // need this option!!
}

试过这个,但对我不起作用。 有什么想法吗?

现在这是我的职能和

使用 JS:

$(element).attr('onclick', 'return false'); // disable
$(element).removeAttr('onclick'); // enable

目录

<a href="http://www.google.com" onclick="return false">google</a>

对元素使用"off"调用

$(element).off('click');

它们可以通过"开"反弹

$(element).on('click', function(){
    //your handler
});

您可以使用 $el.off('click') 停止特定事件的处理程序。

请注意,重新附加事件可能会很长,因此最好在处理程序本身中使用标志来指导逻辑。像这样:

$el.click(function(e) {
    var $el = $(this);
    if ($el.data('click-disabled')) {
        e.preventDefault();
    } 
    else {
        // do your thing...
    }
}

然后,您可以通过设置 data 属性来禁用/启用处理程序逻辑:

$el.data('click-disabled', true);

您是否采取了错误的方法?如果有可能重新附加,为什么要删除处理程序?

始终连接处理程序可能更合适,然后检查您认为意味着删除的任何条件

$('#someThing').on('click', function () {
    if(!someConditionThatYouFeelShouldRemoveTheHandler){
        // do some code here
    }
});

这样,您无需多次附加和重新连接

答案 2

$(document).ready(function() {
    $('.ui-disabled').click(function(e) {
        e.preventDefault();
    });
});
function disableElement(element, tooltip) {
    $(element).addClass('ui-disabled');
    // do nothing
    if (typeof tooltip != 'undefined' && tooltip != "")
        loadTooltip(element, tooltip);
}
//enable element (remove disable class and bind to click eventl
function enableElement(element) {
    $(element).removeClass('ui-disabled');
    $(element).prop("title", "");
    // do nothing
}