繁体   English   中英

空div不显示JavaScript输出? (……至少我认为是问题所在)

[英]Empty div not displaying JavaScript output? (… at least I think that's the issue)

我对编码还很陌生,而且我已经有一段时间没有练习这些语言了,所以这可能是一个很愚蠢的问题。 我正在尝试使用教程制作一个随机生成器,但是在完成项目时遇到了一些问题。

我的JavaScript是

function generator() {

  var ideas = ["design it for meerkats", "make it twice as big and half as loud", "use the rainbow filter in photoshop", "design using sound", "must not have a conscious or unconscious gender bias", "make it appeal to dogs", "make it so it can be unmade"];

  var randomNumber1 = parseInt(Math.random() * ideas.length);

  var command = ideas[randomNumber1];

  //alert(command);

};


//generator();

 if(document.getElementById("result")){
 document.getElementById("placeholder").removeChild(document.getElementById("result"));
  }
  //A div element is created to show the generated name.
  //The Name is added as a textnode. Textnode is added to the placeholder.
  var element = document.createElement("div");
  element.setAttribute("id", "result");
  element.appendChild(document.createTextNode(command));
  document.getElementById("placeholder").appendChild(element);

我的HTML是

<body onload=”generator()”>
    <div id="generator">
        <div id="placeholder"></div>
        <input type="button" value="Click here!" onclick="generator()" />
    </div>

在教程(和演示中)中,随机生成的文本显示在“占位符” div中。 但是,当我尝试运行代码时,文本永远不会显示,仅显示按钮,单击该按钮不会执行任何操作。 我已经回过本教程很多次了,我觉得我必须错过一些非常明显的东西。

将文本放在div中的代码不在generator函数的范围内。 这是单击按钮时调用的函数

function generator() {

  var ideas = ["design it for meerkats", "make it twice as big and half as loud", "use the rainbow filter in photoshop", "design using sound", "must not have a conscious or unconscious gender bias", "make it appeal to dogs", "make it so it can be unmade"];

  var randomNumber1 = parseInt(Math.random() * ideas.length);

  var command = ideas[randomNumber1];

  if(document.getElementById("result")){
   document.getElementById("placeholder").removeChild(document.getElementById("result"));
  }
  //A div element is created to show the generated name.
  //The Name is added as a textnode. Textnode is added to the placeholder.
  var element = document.createElement("div");
  element.setAttribute("id", "result");
  element.appendChild(document.createTextNode(command));
  document.getElementById("placeholder").appendChild(element);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM