【问题标题】:When running a function again it does not read global array再次运行函数时,它不会读取全局数组
【发布时间】:2016-12-21 06:59:22
【问题描述】:

我是编码和 StockOverflow 的初学者。这是我的第一篇文章,如果我的文章格式不正确,请原谅,因为我只是一名初中生。然而,在那张纸条上,我对下面的代码有疑问。只是一点背景,这段代码应该生成一个财富列表并附加每个财富,然后一旦它遍历整个列表,它就会以随机顺序重新生成一个新的。 (参考下面的代码)问题发生在anotherFortune()。当此函数重新运行generateFortuneCookie() 时,它似乎第二次没有从 fortunesList 数组中提取任何值。它 console.logs 为,“你会的。”此外,它不会重新生成第三个列表,谷歌浏览器会给出以下错误。

app.js:33 Uncaught TypeError: 无法在“Node”上执行“appendChild”:参数 1 不是“Node”类型

大约 10 次后单击按钮时。请注意,我还没有学过 jQuery,所以我更喜欢 JavaScript 解决方案。

JavaScript 代码如下:

    var fortunesList = ["die 2mrrw", "find a dollar", "become poor", "jump off a cliff", "turn into Batman"];
    //if any fortunes are added to the list above, make sure to change "for loop" paramter one value (var i = " ";) and stats function at bottom
    function generateFortuneCookie(){ //runs for the first time button is pressed
      var cloneList = fortunesList.slice();

      //randomizer for fortunes
      var randomFortune = " ";
      for (var i = 4; i >= 0; i--){       
        randomFortune = cloneList.splice(Math.floor(Math.random() * (i + 1)), 1); //(i + 1) ensures 5 values are returned since the last value in math.random is excluded
        console.log("You will " + randomFortune + ".");
        //temporarily stores random list
        var tempCache = document.getElementById("fortune-cache");
        var nodeone = document.createElement("DIV");
        nodeone.innerText = "You will " + randomFortune + ".";
        tempCache.appendChild(nodeone);
      }

      //changes button to prevent a new list of variables from being created
      document.getElementById("first").style.display = "none";
      document.getElementById("second").style.display = "block";

      //appends last fortune from "fortune-cache" into "fortune-cookie-text"
      var cookieText = document.getElementById("fortune-cookie-text");
      var nodetwo = tempCache.lastChild;
      cookieText.appendChild(nodetwo);
    }

    var count = 0;
    var max = fortunesList.length;
    //variables above pertain to the "count" function that reruns the "generateFortuneCookie()" function
    var heightCount = 0;
    //must be seperate and increase OUTSIDE of function, determines div height (dynamicDiv)
    function anotherFortune(){ //this should run only after the first fortune is produce
      var cookieText = document.getElementById("fortune-cookie-text"); //this variable MUST go before nodethree otherwise if declared after, nodethree won't recognize variable
      //appends text from "fortune-cookie-text" to "previous-fortunes", this must be run first before adding new text from tempCache
      var nodethree = document.createElement("LI");
      nodethree.appendChild(cookieText.lastChild); 
      document.getElementById("previous-fortunes").appendChild(nodethree);

      //button counter
      count++
      //console.log(count);
      if(count == max){ //once it runs out of fortunes, it will regenerate a new list
        generateFortuneCookie();
        count = 0; //resets count back to zero
      }

      //this increases div height as list increases
      var dynamicDiv = document.getElementById("other-fortunes-div");
      var height = dynamicDiv.clientHeight;
      heightCount++
      //console.log(heightCount);
      if(heightCount >= 2){
        dynamicDiv.style.height = height + 1 + "px";
      }

  //appends text from "fortune-cache" into "fortune-cookie-text", runs after appending text into "previous-fortunes"
  var tempCache = document.getElementById("fortune-cache");
  var nodetwo = tempCache.lastChild;
  cookieText.appendChild(nodetwo);
}

HTML 代码如下:

<!DOCTYPE html>
<html>
<head>
  <title>Fortune Cookie Gen</title>
  <script type="text/javascript" src="./JS/app.js"></script>
  <link rel="stylesheet" type="text/css" href="./CSS/styles.css">
  <meta charset="utf-8">
</head>
<body>
  <button onclick="generateFortuneCookie()" id="first">Make My Fortune!</button>
  <button onclick="anotherFortune(); stats();" id="second">Generate Another Fortune!</button>
  <div id="fortune-cache">
  </div>
  <div id="fortune-cookie-text">
    <h3>Your Fortune</h3>
  </div>
  <div id="other-fortunes-div">
    <h3>Previous Fortunes</h3>
      <ul id="previous-fortunes">
      </ul>
  </div>
  <div id="statistics">
    <h3>Fortune Statistics</h3>
    <div id="one">

    </div>
    <div id="two">

    </div>
    <div id="three">

    </div>
    <div id="four">

    </div>
    <div id="five">

    </div>
  </div>
</body>
</html>

【问题讨论】:

  • 只需使用slice 而不是splice
  • 在旁注中,以“我是 StockOverflow 的新手”开头并拼错网站名称非常棒。

标签: javascript html css arrays function


【解决方案1】:

由于splice 方法,您的fortunesList 列表被“剪切”并丢弃其元素,因此在第一次调用generateFortuneCookie() 后,数组被清空。我的建议是你在 generateFortuneCookie() 的开头使用一个临时数组,并在每次调用 generateFortuneCookie() 时将 fortunesList 元素传递给临时数组。

如果我的解释很糟糕,只需将这一行添加到 generateFortuneCookie()

var tempList = fortunesList;

并用 tempList 替换 generateFortuneCookie() 中的每个 fortunesList 引用。

或者,您可以使用slice 代替splice

如果这对你有用,请告诉我。

更新

好的,我决定使用你的 fortuneList 的克隆列表,它似乎可以工作。

function generateFortuneCookie(){ //runs for the first time button is pressed
  var cloneList = fortunesList.slice();
  //randomizer for fortunes
  var randomFortune = " ";
  for (var i = 4; i >= 0; i--){       
    randomFortune = cloneList.splice(Math.floor(Math.random() * (i + 1)), 1); //(i + 1) ensures 5 values are returned since the last value in math.random is excluded
    console.log("You will " + randomFortune + ".");
    //temporarily stores random list
    var tempCache = document.getElementById("fortune-cache");
    var nodeone = document.createElement("DIV");
    nodeone.innerText = "You will " + randomFortune + ".";
    tempCache.appendChild(nodeone);
  }

  //changes button to prevent a new list of variables from being created
  document.getElementById("first").style.display = "none";
  document.getElementById("second").style.display = "block";

  //appends last fortune from "fortune-cache" into "fortune-cookie-text"
  var cookieText = document.getElementById("fortune-cookie-text");
  var nodetwo = tempCache.lastChild;
  cookieText.appendChild(nodetwo);
}

【讨论】:

  • 感谢您的回复,但是使用 slice 只会产生“你会的”。在控制台的意思上,它不是读取随机财富。同样使用 tempList 会产生相同的结果,并且第二次无法正常运行,只给出“You will”的输出。也。
  • @zak.s_ 你能提供一个包含你的代码的 jsfiddle 链接,以便我调查你的问题吗?
  • 我将粘贴的代码复制到 JS fiddle jsfiddle.net/1bbLeyqa/1
  • 如果 JS fiddle 似乎不起作用,我在 github 中的这个项目的 repo 是 'github.com/zakattack9/fortune-cookie-generator' 在那里查看代码可能更容易。
  • 这是正确的链接,github.com/zakattack9/fortune-cookie-generator 抱歉。
猜你喜欢
  • 1970-01-01
  • 2020-05-25
  • 2015-02-13
  • 2014-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-05
相关资源
最近更新 更多