按下按钮时清除段落文本

时间:2016-12-03 23:29:58

标签: javascript button text clear

我无法按下按钮来清除文字。因此,当我单击图像时,按钮和文本会显示,当我单击按钮时它会消失但文本没有。

<script type="text/javascript">
  function song(animal, sound) {
    document.getElementById("buttonAppear").innerHTML = '<button type="button" onclick="buttonFunction(); clear();">Clear</button>';
    document.getElementById("verse").innerHTML += "<br>Old MacDonald had a farm, E-I-E-I-O.<br>And on that farm he had a " + animal + ", E-I-E-I-O.<br>with a " + sound + "-" + sound + " here and a " + sound + "-" + sound + " there,<br>  here a " + sound + " there a " + sound + " everywhere a " + sound + "-" + sound + ".";
  }

  function clear() {
    document.getElementById("verse").innerHTML = "";
  }

  function buttonFunction() {
    document.getElementById("buttonAppear").innerHTML = "";
  }
</script>
</head>
<main>
  <h1>The Animals Game</h1>

  <img src="cat.jpg" title="Cat" alt="Cat" height="200" width="200" onclick="song('CAT', 'MEOW') ;">
  <img src="cow.jpg" title="Cow" alt="Cow" height="200" width="200" onclick="song('COW', 'MOO') ;">
  <img src="dog.jpg" title="Dog" alt="Dog" height="200" width="200" onclick="song('DOG', 'WOOF') ;">


  <p id="verse"></p>
  <div id="buttonAppear"></div>

2 个答案:

答案 0 :(得分:1)

事实证明,作为文档对象的属性,已经采用'clear'作为全局引用。

更多信息:

Is "clear" a reserved word in Javascript?

您应该将您的函数名称更改为其他名称,例如clearParagraph()

答案 1 :(得分:0)

当调用onclick处理程序时,您没有引用clear函数,而是引用document.clear函数(Is "clear" a reserved word in Javascript?)。尝试重命名您的函数设置点击事件处理程序,而不是使用onclick属性(您可以在此处详细了解onclick="" vs event handler,并列出类似的问题)