簡體   English   中英

如何在滿足特定條件后僅執行一次代碼?

[英]How to execute a code only once after a certain condition has been met?

我想發生的是,一旦窗口達到某個寬度(1023px),就交換2個div的內容,但是我不希望它在每次到達窗口后再調整大小時都繼續運行交換代碼該寬度(1023像素):

$(window).resize(function() {

  if($(window).width() <= 1023) {      

    var $left_col = $('.about-left-col').html();
    var $right_col = $('.about-right-col').html();

    $('.about-right-col').html($left_col);
    $('.about-left-col').html($right_col);

  } 

});

使用==

$(window).resize(function() {

  if($(window).width() == 1023) {      

    var $left_col = $('.about-left-col').html();
    var $right_col = $('.about-right-col').html();

    $('.about-right-col').html($left_col);
    $('.about-left-col').html($right_col);

  } 

});

您可以設置一個簡單變量(在調整大小函數上方)並進行檢查。

var wasResized = false;

調整大小時將其設置為true,並在條件為true / false時添加檢查。

使用全局變量存儲狀態

var notChanged = true;

$(window).resize(function() {

  if($(window).width() <= 1023) {      
    if(notChanged) {//test if its not changed
    var $left_col = $('.about-left-col').html();
    var $right_col = $('.about-right-col').html();

    $('.about-right-col').html($left_col);
    $('.about-left-col').html($right_col);
     notChanged = false;//set it to false so the code doesn't trigger anymore 
    }
  } 

});

你可以這樣嘗試

$(window).resize(function() {

      if($(window).width() <= 1023) {      

        var $left_col = $('.about-left-col').html();
        var $right_col = $('.about-right-col').html();

        if($('.about-right-col').html() != $left_col){
            $('.about-right-col').html($left_col);
            $('.about-left-col').html($right_col);
        }else{
            return false;
        }
      } 

});

您可以執行類似的操作,使用閉包對函數執行進行計數,然后根據需要進行操作。

 $(window).resize(reposition); function reposition = ({ var count = 0; return function() { if (count !== 0) { return; } if ($(window).width() <= 1023) { var $left_col = $('.about-left-col').html(); var $right_col = $('.about-right-col').html(); $('.about-right-col').html($left_col); $('.about-left-col').html($right_col); count++; } }; })(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM