当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《空div不显示JavaScript输出?(至少我认为这是问题)》经验,为你挑选了1个好方法。

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

我的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是


    

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



1> Musa..:

将文本放在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);
}

推荐阅读
可爱的天使keven_464
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有