繁体   English   中英

使用 jQuery 单击后禁用链接

[英]disable a link after click using jQuery

我有许多链接(A 元素)样式为“btn”类的按钮,当单击其中一个按钮时,我希望禁用该特定按钮。 此代码不起作用:

$('.btn').on('click', function(e) {
    $(this).prop('disabled',true);
});

有大量教程可以防止表单提交按钮的默认事件,然后禁用它,但这并不是我所需要的......

显然,我的$this没有指向正确的对象,或者其他东西 =)

- - - - - - 更新 - - - - - - - -

抱歉,以上更新。 我拥有的元素不是按钮,它是一个按钮样式的链接......

不要尝试禁用 Anchor 标签。 尝试设置 href 。

$('.btn').on('click', function(e) {
    e.preventDefault();
    $(this).off("click").attr('href', "javascript: void(0);");
   //add .off() if you don't want to trigger any event associated with this link
});

您只需要停止链接中的默认事件。

$('.btn').on('click', function(e) {
    $(this).prop('disabled',true);
    e.preventDefault();
});

这对我有用:

$('a').css("pointer-events", "none");

它工作正常。

 $('.btn').on('click', function(e) { $(this).prop('disabled',true); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <button class='btn'>But1</button> <button class='btn'>But2</button> </div>

除了使用this ,您可以使用它的id来指定您的目标。

 $('.btn').on('click', function(e) { $('#btn2').prop('disabled',true); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id="btn1" class="btn">Button</button> <button id="btn2" class="btn">Button</button> <button id="btn3" class="btn">Button</button>

希望能帮助到你

$('.btn').on('click', function(e) {
    $(this).attr('disabled', true);
});

检查这篇文章: https ://stackoverflow.com/a/5876747/5243272

这有效(在 chrome 中),但也许有一些缺点?

        $('.btn').on('click', function(e) {
            if( $(this).prop('disabled') == true) {
                return false; 
            }

            $(this).prop('disabled',true);

        });
$(document).ready(function() {
  $('.btn').on('click', function(e) {
    e.stopPropagation();
    e.preventDefault();
    alert('I have been clicked!');
    $(this).css('pointer-events', 'none').css('cursor', 'default');
  });
});

这将阻止对该链接的任何其他进一步点击。

如果你的 HTML 像这样

<a href="https://www.google.co.in/" target="_blank" class="test">This      is another paragraph.</a>

使用下面的代码:

$(".test").one("click", function() {
    var clas = $(this).attr("class");
    setTimeout(function() {
        $("." + clas).removeAttr('href');
    }, 100);
});

如果你的 HTML 像这样

<a href="https://www.google.co.in/" target="_blank" class="test"> <button class="btn">This is another paragraph.</button></a>

使用下面的代码:

$(".btn").one("click", function() {
    var clas = $(this).parent().attr("class");
    setTimeout(function() {
        $("." + clas).removeAttr('href');
    }, 100);
});

就我而言,我使用了以下内容:

onclick="$(this).css('pointer-events', 'none');"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM