为什么每次通话都翻倍

Why are the calls doubling each time?

本文关键字:为什么      更新时间:2023-09-26

显示在这里: JS 小提琴

这是我们关注的代码:

    doit1();
    function doit2(){
        $("#evtTarget").on("click", function(evt) {
            $("#evtTarget").addClass("highlighted");
            $("#evtTarget").on("mouseover mouseleave", highlight);
            $("#evtTarget").html("<p>You Turned on the hover effect!</p>");
            doit1();
        });}
    function doit1(){
        $("#evtTarget").on("click", function(evt) {
            $("#evtTarget").off("mouseover mouseleave", highlight);
            $("#evtTarget").html("<p>You shut off the hover effect!</p>");
            $("#evtTarget").removeClass("highlighted");
            console.log("check");
            doit2();
        });}

关于这段代码的一些东西,我无法弄清楚,来回调用并每次加倍调用。这最终会破坏页面。为什么会这样,我怎样才能做得更好?

你的代码有点"可重入"...您只需要设置一次点击...

尝试:

$(function() {
  turnItOn();
  $("#evtTarget").on("click", function(evt) {
    if ($("#evtTarget").hasClass("highlighted")) {
      turnItOff();
    } else {
      turnItOn();
    }
  });
});
function turnItOn() {
  $("#evtTarget").addClass("highlighted");
  $("#evtTarget").on("mouseover mouseleave", highlight);
  $("#evtTarget").html("<p>You Turned on the hover effect!</p>");
}
function turnItOff() {
  $("#evtTarget").off("mouseover mouseleave", highlight);
  $("#evtTarget").html("<p>You shut off the hover effect!</p>");
  $("#evtTarget").removeClass("highlighted");
}
function highlight(evt) {
  $("#evtTarget").toggleClass("highlighted");
}

正如在这个版本的你小提琴中看到的:

https://jsfiddle.net/pnz9eooz

或者关闭事件,就像阿隆在我写这:)时建议的那样

在这两个函数上,将$("#evtTarget").on("click", function(evt) {更改为$("#evtTarget").off( "click" ).on("click", function(evt) {