【问题标题】:Submit Button Javascript closes form on any button not just on submit提交按钮 Javascript 关闭任何按钮上的表单,而不仅仅是提交
【发布时间】:2019-06-24 19:38:24
【问题描述】:

我的问题是,带有 javascript onclick 事件的提交按钮即使在我点击表单中的某个字段时也会被触发,而不仅仅是提交按钮事件。

<html>
<body>

<div id="showKontakt" style="position: absolute; top: 40px; left:33%; display:none">
<form class="formoid-solid-blue" style="background-color:#FFFFFF;font-size:14px;font-family:'Roboto',Arial,Helvetica,sans-serif;color:#34495E;max-width:680px;min-width:150px" method="post"><div class="title"> 
<h2>Kontaktformular</h2></div>
<div class="element-name"><label class="title"><span class="required">*</span></label><span class="nameFirst"><input placeholder=" Vorname" type="text" size="8" name="name[first]" required="required"/><span class="icon-place"></span></span><span class="nameLast"><input placeholder=" Nachname" type="text" size="14" name="name[last]" required="required"/></div>

<button class="submit" style="margin-left: 33%; width: 175px; margin-bottom:20px"><input type="submit" value="Absenden" onclick="closeFrame()"/> 
</button></form>
</div>
<button style="text-align: center;width:60%;margin-left:20%" onclick="setVisibility('showKontakt', 'inline');">Jetzt informieren</button>
<script language="JavaScript">
function setVisibility(id, visibility) {
document.getElementById(id).style.display = visibility;
}
</script>

<script type="text/javascript">
function closeFrame() {
document.getElementById("showKontakt").style.display="none";
}
</script>

</body>
</html>

预期结果:表单仅在我单击提交按钮时关闭。

实际结果:当我点击输入字段时,表单也会关闭。

【问题讨论】:

  • 我怀疑这就是正在发生的事情。它只是提交表单,它会重新加载整个页面。
  • 在函数中添加控制台日志,点击其他按钮时不会看到消息。
  • 1.不,我点击例如。名称字段,它也会关闭表单(显示:无)。 2. 控制台除了页面加载时间之外不提供任何信息。
  • 你能做一个minimal reproducible example 来演示这个问题吗?
  • 如果您在函数中添加了console.log("closeFrame called"),并且在控制台中看不到该消息,那么显然它没有运行该函数。表单被其他东西隐藏了。

标签: javascript html


【解决方案1】:

没有理由在button 中提交输入。试试这个,因为我认为这是你假装的

function closeFrame() {
  document.getElementById("showKontakt").style.display="none";
}
<form name="myForm">
  <div id="showKontakt">
    Name: <input type="text" name="fname">
  </div>
  <input type="submit" value="Absenden" onclick="closeFrame()"/> 
</form>

如果您不想让按钮消失,您可以创建一个按钮,但在表单之外

function closeFrame() {
  document.getElementById("showKontakt").style.display="none";
}
<form name="myForm">
  <div id="showKontakt">
    Name: <input type="text" name="fname">
  </div>
</form>

<button onclick="closeFrame()">Absenden</button> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-07
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 2016-10-01
    • 2014-03-23
    相关资源
    最近更新 更多