点击事件撤消

时间:2019-03-10 17:47:06

标签: javascript jquery html css

我正在第一个网站上工作,但点击事件有问题。

这是我的网站(未完成):https://pawcio93.github.io/PortfolioSinglePage/

问题是#cancel不起作用(单击后运行功能,我用警报对其进行了检查,但是click事件并不能完全撤消自身。我也尝试使用.on .off方法,但结果相同。这是在做错事,还是我不能使用这些方法正确地取消此“点击”功能?如果没有,该如何执行呢?在此先感谢您的答复,我将自己弄清楚,等待您的提议

var chooseHobby = function() {
  $(this).addClass('hobbyOnClick').removeClass('hobby firstInLine hobbyImg');
  $('.hobbyImg').hide();
  $('.hobby').css('display', 'none');
  updateHeight2();
  var id = this.id;

  if (id == 'sport') {
    if (document.getElementById("gym")) {
      return;
    } else {
      $('#sport').append('<img id="runmaggedon" src="img/runmaggedon.jpg" alt="runmaggedon" />');
      $('#sport').append('<img id="gym" src="img/gym.jpg" alt="gym" />');
      $('#sport').append('<div class="sportText">\n\
            <p>Runmaggedon is my hobby for over a year, it is challenging, hard and the people and athmosphere there is just great. For now my best distance is 24 km in mountain terrain, but it was not my last word! </p>\n\
            \n\
            </div>');
      $('#sport').append('<div class="sportText"><p>Working out is something that I&#39m doing since studies. It is became the part of my daily routine, I love to work with my body and see physical ad power progress. Gym also help with self-discipline and well-being </p></div>');
      $('#sport').append('<div id="cancel"><p>CANCEL</p></div>');
    }
  } else if (id == 'travel') {
    alert("travel");
  } else if (id == 'objectivism') {
    alert("objectivism");
  } else if (id == 'engineering') {
    alert("engineering");
  } else if (id == 'programming') {
    alert("programming");
  } else if (id == 'economy') {
    alert("economy");
  }

  $("#cancel").bind("click", function() {
    alert("function start");
    $(".hobby").unbind("click", chooseHobby);
  });
};

$(document).ready(function() {
  $(".hobby").bind('click', chooseHobby);
});

1 个答案:

答案 0 :(得分:1)

click是一个事件。用户点击后,发生的时间为毫秒(即刻)。

您不能“撤消”

对于该事件,您可以注册要执行的功能。现在要“撤消” 此类功能所做的更改,您必须存储以前的相关状态/值。并使用另一个click事件,您可以给出撤消的印象

这是一个非常简单的示例,仅更改了<h1>文本。

// Store initial text.
var previousH1state = $("h1").text();

// Modify
$("#modify").on("click",function(){
  $("h1").text("I'm modified!");
});

// Undo
$("#undo").on("click",function(){
  $("h1").text(previousH1state);  // Notice the stored text is used here.
});

// De-register functions tied to click events from the modify/Undo buttons.
$("#off").on("click",function(){
  $("#modify, #undo").off("click");
  console.log("Modify and Undo buttons are not working anymore");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1>I'm unchanged.</h1>

<button id="modify">Modify the header above</button>
<button id="undo">Undo the modification</button><br>
<br>
<button id="off">Use .off()</button>

.off()用于从元素上的事件注销功能。那是另一回事...

有关events的更多信息。