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

标签 javascript html

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

我的 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);
}

关于javascript - 空 div 不显示 JavaScript 输出? (......至少我认为这是问题所在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34276940/

相关文章:

javascript - Aurelia CLI 和 Gulp Shell

javascript - 自动完成 jQueryUI 出现在 IE 中可见屏幕的下边缘下方

html - 我可以使用纯 CSS 根据 URL 的获取参数设置链接样式吗?

javascript - 在 HTML 中隐藏部分直到打开

javascript - React App - 我的警告窗口出现两次

javascript - 我应该添加什么过滤器以在 Netsuite - suitescript 的最后 14 或 15 天内获得相同的 transaction_date 字段?

javascript - 鼠标移出时隐藏菜单

javascript - 修改 autoscroll &lt;input&gt; 必需属性 HTML

javascript - 如何在html页面上打印一些javascript代码

html - 如何调整 DIV 大小以匹配屏幕大小 :