如何防止默认和禁用一个href

How to preventDefault and disable a href

本文关键字:一个 href 何防止 默认      更新时间:2023-09-26

在第一次点击我的按钮点击功能工作,但再次点击它刷新页面点击取消绑定不被识别。我需要防止任何默认的点击事件以及禁用按钮后点击。

<a href="" class="red-btn2">Save this Property</a>
$(".red-btn2").click(function(event){
  event.preventDefault();
  $(this).unbind('click');
  $(this).css({
    'background-color':'#666666',
    'text-align':'center'
  });
  $(this).text("Added to Favorites");
});

如果您需要处理程序的其余部分只运行一次,但preventDefault()总是运行,您可以将它们分成多个处理程序。

然后,其中一个可以在第一次使用后被删除(使用jQuery的.one()将为您覆盖),仍然留下使用的preventDefault():

$('.red-btn2')
    .click(function (event) {
        event.preventDefault();
    })
    .one('click', function () {
      $(this).css({
        'background-color':'#666666',
        'text-align':'center'
      });
      $(this).text("Added to Favorites");
    });

正如您所拥有的,event.preventDefault()也被.unbind('click')删除,因此在元素上没有留下任何函数来调用它进行第二次单击。

当您解除绑定处理程序时,该按钮将在任何后续单击中正常运行,并启动导航。所以你最好设置disabled属性:

$(".red-btn2").click(function(event){
  event.preventDefault();
  if ($(this).prop('disabled')) return; // <---
  $(this).prop('disabled', true); // <----
  $(this).css({
    'background-color':'#666666',
    'text-align':'center'
  });
  $(this).text("Added to Favorites");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="" class="red-btn2">Save this Property</a>

注意event.preventDefault()实际上工作。只有在第二次点击时你才会遇到问题,因为链接仍然是可点击的,但是你的功能与它分离了,所以你无法控制第二次点击。