Run javascript function only once

后端 未结 3 1982
不知归路
不知归路 2020-12-10 21:48

I have this simple javascript function:



        
相关标签:
3条回答
  • 2020-12-10 21:56

    Write the code as follows:

    <script type="text/javascript">
        var popup = '0';
    
         $(document).ready(function () {     
              $(document).on('click', '.button', function(){
                 if(popup == '0') {
                    alert('test');
                    popup = '1';
                 }
              });
         }); 
    </script>
    

    Once your click listener is set, your previous if statement's location wasn't executed anymore. Only the code inside the on click function.

    Alternatively, you can unbind the onClick listener instead of setting popup = '1'. Try the following:

    <script type="text/javascript">
        var popup = '0';
    
         $(document).ready(function () {     
              $(document).on('click', '.button', function(){
                  alert('test');
    
                  //unbinds *all* listeners previously registered on "document"
                  $(document).unbind('click');
              });
         }); 
    </script>
    

    Much cleaner, and as Mathletics has mentioned, cleans unnecessary callbacks from memory.

    0 讨论(0)
  • 2020-12-10 21:56

    Try:

    <script type="text/javascript">
        var popup = '0';
    
           $(document).ready(function () {     
                $(document).on('click', '.button', function(){
                    if(popup == '0') {
                      alert('test');
                    }
                      popup = '1';
                });
           }); 
    </script>
    

    You had a function that was setting popup to 1 but was never checking its value again. This way it gets checked and should work properly.

    0 讨论(0)
  • 2020-12-10 22:21

    What you need is .one() function. It makes sure the code is triggered only once for you.

    Docs: http://api.jquery.com/one/

    Docs example:

    $( "#foo" ).one( "click", function() {
      alert( "This will be displayed only once." );
    });
    
    0 讨论(0)
提交回复
热议问题