簡體   English   中英

只運行一次腳本

[英]Run script only once

我有這樣的表格:

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

以及防止提交后重定向或重新加載頁面的腳本:

<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>

我需要的是腳本在提交后只運行一次。

您可以為此使用一個

<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>

首先,將類名或 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