有人知道如何在jquery中禁用一个链接而不使用return false吗?

具体来说,我要做的是禁用一个项目的链接,使用jquery执行点击它触发一些东西,然后重新启用该链接,以便如果它再次单击它作为默认工作。

谢谢。 戴夫

更新 这是代码。在应用.expanded类之后,它需要做的是重新启用被禁用的链接。

$('ul li').click(function(e) {
    e.preventDefault();
    $('ul').addClass('expanded');
    $('ul.expanded').fadeIn(300);
    //return false;
});

当前回答

只需设置preventDefault并返回false

   $('#your-identifier').click(function(e) {
        e.preventDefault();
        return false;
    });

这将是禁用链接,但仍然,你会看到一个可点击的图标(手)图标。你也可以删除下面

$('#your-identifier').css('cursor', 'auto');

其他回答

这适用于内联设置了onclick属性的链接。这也允许您稍后删除“返回false”以启用它。

        //disable all links matching class
        $('.yourLinkClass').each(function(index) {
            var link = $(this);
            var OnClickValue = link.attr("onclick");
            link.attr("onclick", "return false; " + OnClickValue);
        });

        //enable all edit links
        $('.yourLinkClass').each(function (index) {
            var link = $(this);
            var OnClickValue = link.attr("onclick");
            link.attr("onclick", OnClickValue.replace("return false; ", ""));
        });

unbind()在jQuery 3中已弃用,请使用off()方法代替:

$("a").off("click");

您可以删除点击链接按以下;

$('#link-id').unbind('click');

您可以通过以下操作重新启用链接,

$('#link-id').bind('click');

不能对链接使用“disabled”属性。

作为后端工程师,我花了一段时间来思考如何做到这一点,但下面是我如何解决完全相同的问题。

const resendCodeTimeOutPeriodInMs = 30000; // 30seconds.

function resend2faCodeOnLogin(sendByEmail) {

const resendCodeLinkElement = $('#resendCodeLink');

const disabledState = resendCodeLinkElement.attr('disabled');
if (disabledState === 'disabled') {
    resendCodeLinkElement.preventDefault();
} else {
    resendCodeLinkElement.attr("disabled", true);
    resendCodeLinkElement.addClass('disabled');

    submitForm('#twoFactorResendCodeForm', (response) => {
        setTimeout(function () {
            $('#resendCodeLink').removeClass('disabled');
            resendCodeLinkElement.attr("disabled", false);
        }, resendCodeTimeOutPeriodInMs); 

    }, (response) => {
        console.error(response);
    });
}
}

标准CSS摘自网络上著名的例子:

a.disabled {
opacity: 0.5;
pointer-events: none;
cursor: default;

我的方法是确保一个给定的按钮在用户体验可以再次点击它之前被禁用30秒。

下面是另一个css/jQuery解决方案,我更喜欢它的简洁和最小化脚本:

css:

a.disabled {
  opacity: 0.5;
  pointer-events: none;
  cursor: default;
}

jQuery:

$('.disableAfterClick').click(function (e) {
   $(this).addClass('disabled');
});