简体   繁体   English

只运行一次脚本

[英]Run script only once

I have the form like this:我有这样的表格:

<form method="POST" action="bubble2.php" id="bubbleName">
    <input id="myInput" name="namehere" type="text">
    <input name="submit" type="submit">  
</form>

And the script which prevents redirecting or reloading the page after submit:以及防止提交后重定向或重新加载页面的脚本:

<script>
$(document).ready(function(){
   $('form').submit(function(e){
    e.preventDefault();

        $.ajax({
            type: 'POST',
            url: 'bubble.php',
            data: $('form').serialize(),
            success: function(data) {

                 $('#bubbleName')[0].reset();

            }
        });

   });
});
</script>

What I need is the script to run only once after submit.我需要的是脚本在提交后只运行一次。

You can use one for that:您可以为此使用一个

<script>
$(document).ready(function(){
   $('form').one('submit', function(e){
    e.preventDefault();

        $.ajax({
            type: 'POST',
            url: 'bubble.php',
            data: $('form').serialize(),
            success: function(data) {

                 $('#bubbleName')[0].reset();

            }
        });

   });
});
</script>

first, add class name or id to the submit button and then add EventListener首先,将类名或 id 添加到提交按钮,然后添加 EventListener

 <form method="POST" action="bubble2.php" id="bubbleName">
   <input id="myInput" name="namehere" type="text">
   <input name="submit" type="submit" class="btn">  
 </form>

document.querySelector(".btn").addEventListener("click",function(){

  //enter your code here

};

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

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