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