简体   繁体   English

只运行一次javascript函数

[英]Run javascript function only once

I have this simple javascript function: 我有这个简单的javascript函数:

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

<button class="button">Test</button>

I want the function to alert only on the first click but it keeps working although I changed the value of popup to 1 我希望函数仅在第一次单击时发出警报但它仍然有效,尽管我将popup的值更改为1

What you need is .one() function. 你需要的是.one()函数。 It makes sure the code is triggered only once for you. 它确保代码仅为您触发一次。

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

Docs example: 文档示例:

$( "#foo" ).one( "click", function() {
  alert( "This will be displayed only once." );
});

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. 设置单击侦听器后,之前的if语句的位置不再执行。 Only the code inside the on click function. 只有点击功能里面的代码。

Alternatively, you can unbind the onClick listener instead of setting popup = '1' . 或者,您可以取消绑定onClick侦听器,而不是设置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. 更简洁,就像Mathletics所提到的那样,可以清除内存中不必要的回调。

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. 你有一个将弹出窗口设置为1的功能但从未再次检查其值。 This way it gets checked and should work properly. 这样它就会被检查并且应该正常工作。

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

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