如何修复下拉按钮(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元素应该包含所有的标记,而不仅仅是其中的一部分。还有,你的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>

这是一个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>

最新更新