removeEventListener-返回False不停止侦听器

时间:2020-10-15 02:51:29

标签: javascript addeventlistener removeeventlistener

我正在监听两个变量heightweight中的变化。当两个都评估为true时,我期望返回值false以停止侦听器。当我将范围滑块移动到代码中的其他位置时,它会继续附加<script type="text/javascript" src="js/modelers/average_aboveaverage.js"></script>

  function makeModeler() {
    document.addEventListener("change", function(){
      var height = document.getElementById('height-class').value; 
      var weight = document.getElementById('weight-class').value;
      shape = height + "_" + weight;
     
      if (!(height && weight)) { 
        return true;

      } else {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "js/modelers/"+shape+".js";

        document.body.appendChild(script);
        return false;        
      }
    });  
   
  }

  makeModeler();

  document.addEventListener("change", makeModeler);
  document.removeEventListener("change", makeModeler, false);

2 个答案:

答案 0 :(得分:0)

自此,您将在每次更改中无限添加事件:

document.addEventListener("change", makeModeler);

makeModeler函数还首先添加了onChange事件

答案 1 :(得分:0)

我必须找到一种非常规的方式来停止eventListener。 eventTarget不适用于我在网站上呈现数据的“动态”方式。注意,addEventListener应该附带一个选项来阻止它无限运行。似乎很明显。

我将监听器添加到一个do / while中:

  var height = document.getElementById('height-class').value; 
  var weight = document.getElementById('weight-class').value;
  
  do {
    document.addEventListener("change", function(){
      
      var height = document.getElementById('height-class').value; 
      var weight = document.getElementById('weight-class').value;

      shape = height + "_" + weight;
     
      if (!(height && weight)) { 
        return true;      

      } else {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "js/modelers/"+shape+".js";

        document.body.appendChild(script);
        document.getElementById('weight-class').id = "weight-class2";
        
      }
      
    });  
  }
  while (height && weight);

我更改了元素的ID,以阻止while条件从评估变为true。更有经验的程序员可能会知道更好的条件来停止这种情况。