为什么我的按钮在我点击它时不执行该功能。它应该切换文本

Why won't my button do the function when I click it it. It should toggle the text

Function

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
  This is my DIV element.
</div>

我在 W3Schools 上找到了这段代码,并将 "myDIV" 替换为 "h3",这样我就可以更改 header

中的文本
    <div class="speech-buble-top"><h3 id="h3"> Happy Birthday Tiffany!</h3></div>

没有脚本标签添加 javascript 标签。

<script type="text/javascript"> your code </script>

您的 JS 函数必须在您的按钮之前声明。并且必须包含在 <script> </script> 标签中

问题源于您使用 function 关键字声明函数。通常这很好,但我发现使用 HTML 调用的 javascript 函数作为已分配给变量的函数更容易。如果你使用 ES6 箭头语法,你将同时使用最新的标准并将函数绑定到一个变量。尝试像这样重写函数代码:

<script>
  myFunction = () => {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
    x.style.display = "block";
} else {
    x.style.display = "none";
   }
}
</script>
<button onclick="myFunction()">Try it</button>
<div id="myDIV" style="display: none">
  <h3 id="h3"> Happy Birthday Tiffany!</h3>
</div>

如果您尝试在网页中嵌入代码,那么是的,您需要确保对所使用的代码类型进行分类。 <style></style> 代表 CSS,<script></script> 代表 Javascript。

您似乎正在尝试执行一个简单的 hide/show 脚本。您应该努力的一件事是代码的效率。您问题中的大块代码可以缩短为:

function toggleHide() {
  var element = document.getElementById("myDIV");
  element.classList.toggle("hide");
}
.hide {
  display: none;
}
<button onclick="toggleHide()">Try it</button>
<div id="myDIV">This is a DIV element.</div>

这是内联的样子:

<style>
.hide {
    display: none;
}
</style>

<button onclick="myFunction()">Try it</button>
<div id="myDIV">This is a DIV element.</div>

<script>
function myFunction() {
   var element = document.getElementById("myDIV");
   element.classList.toggle("hide");
}
</script>

您可以使用 addEventListner() 代替内联 HTML onclick()。试试这个:

var x = document.getElementById("myDIV");
document.getElementById("myBtn").addEventListener('click', function() {
  if (x.style.display == "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
});
#myDIV {
  border: 1px solid black;
  padding: 3px;
}
<button type="button" id="myBtn">Show</button>
<div id="myDIV" style="display: none;">Show the content</div>

注意 x.style.display 检测内联样式 HTML 属性。因此,如果您使用单独的 css 文件来设置 div 的样式,则第一次需要单击两次...