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

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

谢谢。 戴夫

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

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

当前回答

如果您使用href路径,则可以保存它

禁用:

$('a').each(function(){
    $(this).data("href", $(this).attr("href")).removeAttr("href");
});

然后重新启用使用:

$('a').each(function(){
    $(this).attr("href", $(this).data("href"));
});

在一种情况下,我不得不这样做,因为点击事件已经绑定到其他地方,我无法控制它。

其他回答

如果您使用href路径,则可以保存它

禁用:

$('a').each(function(){
    $(this).data("href", $(this).attr("href")).removeAttr("href");
});

然后重新启用使用:

$('a').each(function(){
    $(this).attr("href", $(this).data("href"));
});

在一种情况下,我不得不这样做,因为点击事件已经绑定到其他地方,我无法控制它。

这适用于内联设置了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; ", ""));
        });

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

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秒。

你可以隐藏和显示你喜欢的链接

$(link).hide();
$(link).show();

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

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

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

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

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