【问题标题】:Combining while loop and onclick function in Javascript在Javascript中结合while循环和onclick函数
【发布时间】:2021-11-04 07:22:00
【问题描述】:

我正在尝试在单击原始方块后立即显示新方块。使用此代码,您必须每次重新加载才能出现新的方块。有没有办法将带有布尔值的while循环与javascript中的onclick函数结合起来以实现这一点?代码如下:

var starttime = new Date().getTime();
var topposition = Math.random() * 650;
var leftposition = Math.random() * 650;
var colours = ["red", "blue", "yellow", "green", "brown", "black", "purple", "orange"];
document.getElementById('shape').style.backgroundColor = colours[Math.floor(Math.random() * colours.length)];
document.getElementById('shape').style.top = topposition + "px";
document.getElementById('shape').style.left = leftposition + "px";

document.getElementById("shape").onclick = function() {
  document.getElementById("shape").style.display = "none";
  var endtime = new Date().getTime();
  var timetaken = (endtime - starttime) / 1000;
  document.getElementById("timeTaken").innerHTML = +timetaken + " seconds";
}
#shape {
  width: 200px;
  height: 200px;
  position: relative;
}
<p>Your time: <span id="timeTaken"></span></p>
<div id="shape"></div>

【问题讨论】:

  • 不要使用 while 循环来检查某些内容。它会阻止页面。
  • "我试图在单击原始方块后立即显示新方块。"为什么要避免标准的单击事件侦听器?跨度>
  • 您应该使用您的 JS 逻辑创建一个 function() 并使用事件调用它。以 onlick 为例,developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/…。在您的示例中,该逻辑仅在页面加载后调用一次。
  • 我刚接触编码。那么,我创建了一个在单击原始方块时运行的函数,该函数的指令是创建一个新方块?有没有办法让 1 个元素在您每次单击它时移动、更改颜色并同时启动计时器?我认为我必须从代​​码中删除“display = none”,但由于随机位置在变量内,它不会移动。计时器也只会添加总时间而不是重置,这就是为什么我想到一个循环让它每次都重新启动,并让随机化也重新启动。
  • 更新:每次点击时都能移动并改变颜色。然而,计时器再次只是结合了时间。我想这是因为它在页面加载后立即启动,但我需要它在第一次加载页面时启动,并在单击正方形时重新启动。

标签: javascript while-loop onclick boolean


【解决方案1】:

试试这个,我会在点击时破坏形状并创建一个新的。我也得到并显示一个新的时间。

var startTime = new Date().getTime();
var positionFactor = 650;
var colours = ["red", "blue", "yellow", "green", "brown", "black", "purple", "orange"];
var shapeHolder = document.getElementById("shape-holder");
makeSquare();

function makeSquare ()
{
    starttime = new Date().getTime();
    var topposition = Math.random() * positionFactor;
    var leftposition = Math.random() * positionFactor;
    var square = document.createElement("div");
    square.style.backgroundColor = colours[Math.floor(Math.random() * colours.length)];
    square.style.top = topposition + "px";
    square.style.left = leftposition + "px";
    square.id = "shape";
    shapeHolder.appendChild(square);
    square.onclick = function() 
    {
         var endtime = new Date().getTime();
         var timetaken = (endtime - starttime) / 1000;
         document.getElementById("timeTaken").innerHTML = +timetaken + " seconds";
         var square = document.getElementById("shape");
         square.parentElement.removeChild(square);
         makeSquare();
    }
}
#shape {
  width: 200px;
  height: 200px;
  position: relative;
}
#shape-holder {
  width: 100%;
  height: 100%;
}
<p>Your time: <span id="timeTaken"></span></p>
<div id="shape-holder"></div>

【讨论】:

  • 还可以将 starttime 的重新分配移到 makeSquare 的末尾,这样您就不必同时对该功能进行计时,但这由您决定。
  • 我认为您在示例中遗漏的主要内容是 - 正如其他人所提到的 - 您需要制作一个新方块,或者在点击发生时重新定位/着色您的原始方块。您在 onclick 函数之外编写的代码只会发生一次,单击方块时不会重新运行。
  • 谢谢!这是我最接近我真正想要的东西。唯一的问题是,当您单击 shapeHolder 节点中的任意位置而不是专门单击方形元素时,该函数就会运行。太糟糕了 JS 不允许我们调用函数内部的变量/元素。
  • 我已将 onclick 移至方形/形状。如果这回答了您的问题,请接受它:)
【解决方案2】:

其实你已经做得很好了,只是需要改变一些东西。 首先创建一些函数,以便您可以在需要时再次使用它们,因为在这种情况下您想重置时间和形状的颜色等等,对吗?

我附上修改后的代码我的朋友...

 <html>

      <head>

        <title>javascript</title>

        <style type="text/css">
    
        #shape {

            width: 200px;
            height: 200px;
            position: relative;
            
        }
    
        </style>

     </head>

     <body>
    
       <p>Your time: <span id="timeTaken"></span></p>
    
       <div id="shape"></div>

       <script type="text/javascript">
          //all variables listed as global so that you access them whenever you need...
          var starttime,topposition,leftposition,colours;
          
          //for some reason...it is needed...
          let FirstTime = true;
          
          //init. function for reseting all the parameters like...starttime,position,color etc...
         
          function Initialize()
          {
            starttime = new Date().getTime();

            topposition = Math.random() * 650;

            leftposition = Math.random() * 650;

            colours = ["red", "blue", "yellow", "green", "brown","black","purple","orange"];

            document.getElementById('shape').style.backgroundColor = colours[Math.floor(Math.random() * colours.length)];

            document.getElementById('shape').style.top = topposition + "px";

            document.getElementById('shape').style.left = leftposition + "px";
            
            //if it is not the first time...
            if(!FirstTime)
            {
              //it will also reset the display of id "shape"...
              document.getElementById('shape').style.display = "block";
            }

            //console.log("Init...");//for debugging...
          }
  
          //for recolor(showing the box with id "shape" again...) your web page...
          function Recolor()
          {
            //if it has display "none"
            if(document.getElementById('shape').style.display=="none")
            {
            //again itit...
              Initialize();
              //console.log("Recolor...IF...");
            }
          }
          
          //to draw that "shape" for the first time...
          if(FirstTime)
          {
            Initialize();
            FirstTime = false;
          }
        
          document.getElementById("shape").onclick = function() {             
            
             document.getElementById("shape").style.display = "none";
            
             var endtime = new Date().getTime();

             var timetaken = (endtime - starttime) / 1000;

             document.getElementById("timeTaken").innerHTML = + timetaken + " seconds";
             //modification ....
             Recolor();

          }



       </script>

    </body>

 </html>

我制作并修改了代码有两个函数... 我已经插入了所有的 cmets,以便您了解我修改了什么以及为了什么......

首先,有一个函数......称为“初始化”,用于在 onclick 事件发生时一次又一次地重置所有属性......这样您就不需要重新加载页面...... 为此,我已将所有这些变量设为全局变量,以便您可以随时随地访问。

其次,有一个函数......称为“重新着色”,用于检查如果 id“形状”具有显示属性 none,那么它将再次调用“初始化”函数来重置所有这些属性并再次打印该“形状” .

是的,那个“FirstTime”变量是我制作的,因为只要它是真的..它会调用一次“Initialize”函数,这样当某些事件发生时你就可以使用它假设,只要你按下按钮,你就可以激活那些代码。

【讨论】:

  • 哇,太有帮助了。非常感谢!
猜你喜欢
  • 2018-03-30
  • 1970-01-01
  • 2014-04-30
  • 2012-12-03
  • 2020-09-02
  • 1970-01-01
  • 2013-06-01
  • 1970-01-01
  • 2018-09-25
相关资源
最近更新 更多