【问题标题】:prevent javascript from loading more than once [duplicate]防止javascript多次加载[重复]
【发布时间】:2016-09-05 23:25:49
【问题描述】:

我试图在滚动加载时运行更多,但我希望它只运行一次。每次滚动到达页面底部时,下面的代码都会继续运行。 我需要在代码中添加一些内容

    if ($(window).scrollTop() == $(document).height() -   $(window).height() && x==24 ){

但我不知道要添加什么来使它只运行一次或阻止代码运行多次。

 <script>


    if ($(window).scrollTop() == $(document).height() -   $(window).height() && x==24 ){



   });
 });
 </script>

所以基本上我的问题是如何防止 javascript 运行不止一次。

【问题讨论】:

    标签: javascript php jquery html json


    【解决方案1】:

    如果scroll事件只需要调用一次函数,那么您可以在if语句中使用.off()$(window)中删除scroll事件。

    body {
      height: 400px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>
    <div id="div1">div </div>
    <script>
      x = 24;
    
      $(document).ready(function() {
        $(window).on("scroll.once", function() {
    
          if ($(window).scrollTop() == $(document).height() - $(window).height() && x == 24) {
    
            $(window).off("scroll.once");
            $("#div1").append(123);
    
          }
        });
      });
    </script>

    【讨论】:

    • 让我试试看是否有效
    • 我将在哪里添加此代码。我会添加到 if ($(window).scrollTop() == $(document).height() - $(window).height() && x==24 ){
    • @letsworktogether 查看更新后的帖子,使用$.Callbacks("once")
    • @letsworktogether “让我试试看它是否有效” stacksn-ps 的方法是否返回预期结果?
    • @letsworktogether 如果您已经解决了问题,您可以发布并接受您自己问题的答案,请参阅Can I answer my own question?
    【解决方案2】:

    我有一个简单但不太优雅的解决方案,您可以在函数之前添加boolean flag,在执行函数中的代码之前添加check boolean state。在第一次调用你的函数后更改为愿望boolean state,这样你就可以防止它被再次调用。例如:

    <script>
      var called = false;
    
      function myFunc(){
        if (!called){
          //your code here
          called = !called;
        }
      }
    </script>
    

    这不是最好的答案,但仍然希望对您有所帮助 =)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      相关资源
      最近更新 更多