为什么事件监听器不会改变?

时间:2017-07-12 21:03:51

标签: javascript addeventlistener

代码:



window.onload = function() {
  var a = document.getElementById("q");
  var b = 1;

  function tri() {
    a.style.width = "100px";
    b++
    if (b == 3) {
      b--
    }
    return b;
  }

  function un() {
    a.style.width = "40px"
    if (b == 2) {
      b--
    }
  };
  if (b == 1) {
    a.addEventListener("click", tri);
  };

  if (b == 2) {
    a.addEventListener("click", un)

  };
};

#q {
  width: 40px;
  height: 40px;
  background-color: blue;
}

<div id="q"></div>
&#13;
&#13;
&#13;

我不知道为什么,但我的代码无效。是否可以在一个元素中添加两个事件侦听器?如果是,那么请解释如何。我尝试了很多,但它没有用。

2 个答案:

答案 0 :(得分:0)

您的代码只向DIV添加一个侦听器。它在加载页面时测试b的值,并将tri函数添加为侦听器。当addEventListener的值发生变化时,它永远不会再执行b代码。

您可以向元素添加多个事件侦听器,但在这种情况下无需执行此操作。只需编写一个检查变量的事件监听器。要交替操作,该函数只是反转变量的值。

window.onload = function() {
  var a = document.getElementById("q");
  var small = true; // Is the DIV small or big?

  function change() {
    if (small) { // If it's small, make it big
      a.style.width = "100px";
    } else { // Otherwise, make it small
      a.style.width = "40px";
    }
    small = !small; // invert the value of the variable
  }

  a.addEventListener("click", change)

};
#q {
  width: 40px;
  height: 40px;
  background-color: blue;
}
<div id="q"></div>

答案 1 :(得分:0)

你的程序停留在第一个功能上。你输入1,你就被困在三个。我把你的程序调试成一个悲惨的故事。我称之为迷失为3.点击广场上的悲剧展开。

&#13;
&#13;
var square = document.getElementById("q");
var b = 0;
function triun() {
  if (b === 0) {
    square.style.width = "100px";
    b=1;
  }
   else if (b === 1) {
    square.style.width = "40px"
  b=0;
  };
}

square.addEventListener("click", triun)
&#13;
#q {
  width: 40px;
  height: 40px;
  background-color: blue;
}
&#13;
<div id="q"></div>
&#13;
&#13;
&#13;

&#13;
&#13;
window.onload = function() {
  var a = document.getElementById("q");
  var b = 1;

  function tri() {
  console.log('I want to be 1 but I am fleeting, forever to be two, click once more for my story'+ b +'unfold')
    a.style.width = "100px";
    b++;
    
    console.log(b,' wowe is me, am I 2 or am I 3. All I know, is I will be a tragedy of the click handler that will always fire before the comming of the un')
    if (b == 3) {
      b--
      console.log('I am lost to enter as 3, never will I ever be that 1, lost in time to that fading binary dream I once was but am now', b);
     
    }
    return b;
  }

  function un() {
  console.log(b)
    a.style.width = "40px"
    if (b == 2) {
      b--
    }
  };
  if (b == 1) {
  console.log('I am that first "if", that very first time you dared to dream, what might have been had "un" been here',b )
    a.addEventListener("click", tri);
  };

  if (b == 2) {
  console.log('I am that poor un, I will never be, because 2 will never visit me ');
    a.addEventListener("click", un)

  };
};
&#13;
#q {
  width: 40px;
  height: 40px;
  background-color: blue;
}
&#13;
<div id="q"></div>
&#13;
&#13;
&#13;