如何修复下拉按钮 (HTML)

How do I fix a dropdown button (HTML)

每当我尝试更改此代码中的内容时,我只更改按钮和功能部分,但要么没有任何显示,要么按钮起作用,当我单击按钮时,它应该显示激励评论,对于我正在制作的网站,代码如下:

function myFunction() {
  button.onclick = myFunction;

  document.getElementById("mot").style.visibility = "visible";
}
<button onclick="myFunction()" style="visibility:visible;">Motivation</button>

<body id="mot" style="visibility:hidden;">
  <p>It's harder too read code, then it is too write code</p>
  <p>Practice makes better, not perfect</p>
  <p>Good things take time, the better, the longer</p>

  1. 您的正文元素应包含所有标记,而不仅仅是其中的一部分。另外,您的 body 没有被关闭。

  2. 我用 div 来保存您的评论

  3. button.onclick = myFunction; 不会工作,因为 button 未定义。您还试图在一个已经存在的事件处理程序中添加一个事件处理程序。

function myFunction() 
{
  document.getElementById("mot").style.visibility = "visible";
}
<button onclick="myFunction()" style="visibility:visible;">Motivation</button>

<div id="mot" style="visibility:hidden;">
  <p>It's harder to read code than it is to write code</p>
  <p>Practice makes better, not perfect</p>
  <p>Good things take time, the better, the longer</p>
  
</div>

在jquery中你可以这样做。

$(document).ready(function(){
  $(".motivation").click(function(){
   $("#mot").toggle();
   });
  });
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>

<button class="motivation" style="visibility:visible;">Motivation</button>
<div id="mot" style="display:none">
  <p>It's harder too read code, then it is too write code</p>
  <p>Practice makes better, not perfect</p>
  <p>Good things take time, the better, the longer</p>
 </div>

您的 HTML 标记不符合标准。任何内容都应该在 body 标签内变形。但是,您的代码不需要 button.onclick = myFunction; 该函数已使用 onclick 按钮事件属性调用。

不正确的 标记可能会像这样工作:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script>
    function myFunction() {
  //button.onclick = myFunction;

  document.getElementById("mot").style.visibility = "visible";
}
  </script>
</head>
<button onclick="myFunction()" style="visibility:visible;">Motivation</button>

<body id="mot" style="visibility:hidden;">
  <p>It's harder too read code, then it is too write code</p>
  <p>Practice makes better, not perfect</p>
  <p>Good things take time, the better, the longer</p>  
</body>
</html>

This is a DEMO

要按照 Lee 上面的建议修复标记,请将励志评论放在 div.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script>
    function myFunction() {
  //button.onclick = myFunction;

  document.getElementById("mot").style.visibility = "visible";
}
  </script>
</head>
<body>
<button onclick="myFunction()" style="visibility:visible;">Motivation</button>
<div id="mot" style="visibility:hidden;">
  <p>It's harder too read code, then it is too write code</p>
  <p>Practice makes better, not perfect</p>
  <p>Good things take time, the better, the longer</p>
</div>  
</body>
</html>