我有一个表单,里面有几个div,将某些输入字段组合在一起。我想在页面最初加载时隐藏其中一些div(以及这些div中的输入字段)。这对于css的display:none属性来说很简单。然后,当用户点击显示/隐藏按钮时,我想显示那些隐藏的div及其输入字段。我正在为这个项目使用javascript和css(没有jquery)。
我有一个基本的javascript函数,可以通过单击按钮交替隐藏(显示:无)或显示(显示:阻止)div。当我在测试页面上使用它时,该函数工作正常,其中div不是表单的一部分。但是,当我尝试将这个相同的函数与表单的divs部分(即内部)一起使用时,它不起作用。实际上,它似乎工作,但几乎瞬间恢复到显示设置的初始状态。我有一种感觉,问题在于我的div在一个表单中,但我无法理解为什么这会成为一个问题。我该怎么做才能纠正这个问题,以便表格中的div可以通过按钮的切换来隐藏/显示。
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style>
#random {
width: 600px;
min-height: 50px;
background-color:#E01418;
color:#B5F0B9;
display: block;
}
#hideshow {
width: 600px;
min-height: 50px;
background-color:#223FCD;
color:#F2D595;
display:block;
}
</style>
</head>
<body>
<form id="myform" name="myform" method="post" action="">
<div id="random">
<input type="text" id="firstname" name="firstname" placeholder="firstname">
<input type="text" id="lastname" name="lastname" placeholder="lastname">
<input type="email" id="email" name="email" placeholder="email">
</div>
<div id="hideshow">
<input type="password" id="password" name="password" placeholder="password">
<input type="text" id="address" name="address" placeholder="address">
<input type="text" id="phone" name="phone" placeholder="phone">
</div>
<input type="submit" id="submit" name="submit" value="Update">
<button id="togglehideshow">Hide/Show</button>
</form>
<script>
var button = document.getElementById('togglehideshow');
button.onclick = function() {
var div = document.getElementById('hideshow');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
};
</script>
</body>
</html>
最后一件事 - 我使用的按钮不是表单的提交按钮。我只是不想让任何人与之混淆。感谢您的帮助!
答案 0 :(得分:0)
为显示和隐藏div的按钮添加type =按钮。
<button type="button" id="togglehideshow">Hide/Show</button>
这是因为按钮会在隐藏div后尝试提交表单。