繁体   English   中英

onClick事件在表单标记内不起作用

[英]onClick event doesn't work inside form tag

<!DOCTYPE html>
<html>
    <head>
    </head>
    <script>    
        function removeP2() {
            var parent = document.getElementById("section");
            var child = document.getElementById("p2");
            parent.removeChild(child);
        }
    </script>
    <body>
        <nav>
            <form>
               <button onclick="removeP2();">Remove</button> 
            </form>
        </nav>
        <section id="section">
            <p id="p1">Paragraph One.</p>
            <p id="p2">Paragraph Two.</p>
        </section>
    </body>
</html>

当我单击提交按钮时,该函数照常执行,但在函数执行后,页面重新加载(删除P2一秒钟)。

我找到了一个解决方案,即删除“nav”标签内的“Form”,它工作正常。 只是想问一下问题是什么原因,如果我需要在“nav”标签内加上“Form”标签,我需要修复哪一部分?

表单已提交,您的页面已重新加载。 您需要停止表单提交。

解决方案1:为按钮添加type属性。

<button type="button" onclick="removeP2();">Remove</button>

这将确保该按钮不是submit类型(这是未指定类型时表单标签内按钮的默认类型),并且该表单未在单击时提交。

解决方案2:在javascript中阻止Submit事件。 所以做出这些改变。

<button onclick="removeP2(event);">Remove</button>

并在脚本中阻止此事件

 function removeP2(event) {
   event.preventDefault(); // prevent the event , ie form submit event
   var parent = document.getElementById("section");
   var child = document.getElementById("p2");
   parent.removeChild(child);
 }

解决方案3:我在HTML中看不到表单标签的任何需要。 如果它是您的确切语法,并且您实际上没有表单提交的任何其他元素或目的,那么您可以删除form标记。

 <nav>
   <button onclick="removeP2();">Remove</button>         
 </nav>

请使用以下代码。 它不会提交表格。

<button type="button">My Button</button>

看到这段代码:

https://jsfiddle.net/y7mhu3oL/1/

解决方案是在表单标签中提交:

<script>    
    function removeP2() {
        document.getElementById("p2").remove();
        }   
    </script>
<body>
    <nav>
        <form method="POST" onsubmit="removeP2(); return false;">
           <button>Remove</button> 
        </form>
    </nav>
    <section id="section">
        <p id="p1">Paragraph One.</p>
        <p id="p2">Paragraph Two.</p>
    </section>
</body>

event.preventDefault()是正确的答案。 当您按下表单内的按钮时,它将自动提交该表单,除非您使用event.preventDefault阻止默认操作;

function removeP2(event) {
    event.preventDefault()
    var parent = document.getElementById("section");
    var child = document.getElementById("p2");
    parent.removeChild(child);
}

因为您没有定义按钮type ,所以您的浏览器假定按钮是type="submit"并尝试“提交”表单(即使您尚未定义任何方法或操作)。

如果将type="button"添加到按钮标记,它将覆盖默认的submit假设,并且不会尝试提交表单。

jsfiddle: https ://jsfiddle.net/hdpk8c3n/

type="button"添加到按钮标记。 在表单标记中,按钮的默认类型是提交。 这就是为什么当您单击按钮时,表单已提交并且页面重新加载。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM