【问题标题】:Prevent anchor click after one click防止一键点击锚点
【发布时间】:2015-10-17 13:49:51
【问题描述】:

我面临一个问题,我想在单击后禁用锚点单击。我有 在我的锚标记中设置的点击属性。下面是我的 HTML

<a style="cursor:pointer;" id="someId" onclick="Myfuntion()">Verify</a>     

单击“验证”后,我将锚文本更改为“正在验证...”,还有一件事我试图禁用此锚以避免在验证逻辑之间单击。

我已经尝试过 event.preventdefault() 并且还添加了 disabled 属性到锚点。 但没有任何效果。

请帮忙!

【问题讨论】:

标签: javascript jquery


【解决方案1】:

如果您为此使用 jQuery,您可以更轻松地完成此操作。

在这里,我们向链接添加一个新类,以表明它已被点击。我们会在点击时检查这一点。

&lt;a style="cursor:pointer;" id="someId"&gt;Verify&lt;/a&gt;

$('#someId').on('click',function(){
    //Check if button has class 'disabled' and then do your function. 
    if(! $(this).hasClass('disabled')){
        $(this).addClass('disabled');
        Myfuntion();
        $(this).removeClass('disabled');
    }
});

【讨论】:

    【解决方案2】:

    这是一个关于如何使用 Javascript 完成的演示。

    //Pass the event target to the function
    function Myfuntion(elem) {
    
        //If the element has no "data-status" attribute
        if (!elem.getAttribute("data-status")) {
    
            //Set attribute "data-status=progress"
            elem.setAttribute("data-status", "progress");
            //Change the text of the element
            elem.textContent = "Verifying...";
    
            //The setTimeout(s) below is only for the demp purpose
            //Lets say, your verification process takes 4 seconds
            //When complte
            setTimeout(function() {
                //Remove the attribute "data-status"
                elem.removeAttribute("data-status");
                //Notify the use that verification is done
                elem.textContent = "Verified";
    
                //Again, this is only for demo purpose
                setTimeout(function() {
                    //User may verify again
                    elem.textContent = "Verify";
                }, 1000);
    
            }, 4000);
        }
        return false;
    }
    

    Link to the demo

    【讨论】:

      【解决方案3】:

      有很多方法可以做到这一点;一种简单的方法是重新定义函数本身:

          var myFunction = function() {
              alert('clicked');
              // do whatever your function needs to do on first click, then:
              myFunction = function() { // redefine it 
                  // to no-op, or to another action
                  alert('second click');
              }
          }
      &lt;a onclick="myFunction()"&gt;click me&lt;/a&gt;

      【讨论】:

      • 感谢大家的出色解决方案。我以其他方式解决了它...非常感谢您的帮助
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      • 2020-05-22
      • 2018-01-15
      • 2015-04-28
      相关资源
      最近更新 更多