onClick事件在表单标记内不起作用 [英] onClick event doesn't work inside form tag

查看:125
本文介绍了onClick事件在表单标记内不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<!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一秒钟)。

When I click the submit button, the function executes as usual, but after the function executes, the page reloads itself (removed P2 for a second).

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

I found a solution which is to delete the "Form" inside the "nav" tag, and it works fine. Just want to ask what is the problem cause that, and if I need to have the "Form" tag inside the "nav" tag, which part I need to fix?

推荐答案

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

The form is getting submitted and your page is reloaded. You need to stop the form submit.

解决方案1:添加类型属性到你的按钮。

Solution 1: Add a type attribute to your button.

< button type =buttononclick =removeP2();>删除< / button>

这将确保该按钮不是提交类型(这是默认值如果未指定类型,则在表单标记内键入类型,并且单击时不提交表单。

This will make sure that the button is not of submit type (which is the default type for buttons inside form tag when type is not specified), and that the form is not submitted on click.

解决方案2:防止在javascript中提交活动。所以进行这些更改。

Solution 2: Prevent the Submit event in javascript. So make these changes.

< button onclick =removeP2(event);>删除< / 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中的表单标记。如果它是您的确切语法,并且您在表单提交中确实没有任何其他元素或目的,那么您可以删除表单标记。

Solution 3: I dont see any need of the form tag over there in the HTML. If its the exact syntax of yours and you really dont have any other elements or purpose with the form submission then you can remove the form tag.

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

这篇关于onClick事件在表单标记内不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆