jQuery click() only once

丶灬走出姿态 提交于 2021-01-28 06:51:26

问题


I want to make it so that this button can be clicked only once. If someone clicks it more times then the function will not be performed. How can I do that?

$(".btn_ranking").click(function(e) {
  e.preventDefault();
  var name = localStorage.getItem('name');
  var time = localStorage.getItem('timer_end');

  $.ajax({
    url: "php/file.php",
    method: "POST",
    data: {
      name: name,
      time: time
    }
  })
});

回答1:


Use one() to attach the event handler:

$(".btn_ranking").one('click', function(e) {
  e.preventDefault();
  var name = localStorage.getItem('name');
  var time = localStorage.getItem('timer_end');

  $.ajax({
    url: "php/file.php",
    method: "POST",
    data: {
      name: name,
      time: time
    }
  });
});



回答2:


In addition to Rory's answer, you can also do one of these:

I can't tell from your code here what your markup is, but if your .btn_ranking element is a <button /> tag, then in your click function you can also add a disabled attribute to the button, which should prevent it from being clicked again. https://www.w3schools.com/tags/att_button_disabled.asp

Another thing you can do is add an inline style to that same element of pointer-events: none;

A caveat for ALL of these solutions is that they can be circumvented by simply refreshing the browser.



来源:https://stackoverflow.com/questions/51403168/jquery-click-only-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!