[英]How to execute a code only once after a certain condition has been met?
What I'd like to happen is to swap the content of 2 divs once the window has reached a certain width (1023px) but I don't want it to keep running the swapping code every time I resize the window after it has already reached that width (1023px): 我想发生的是,一旦窗口达到某个宽度(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);
}
});
Use ==
使用==
$(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);
}
});
You can set a simple variable (above you resize function) and check against it. 您可以设置一个简单变量(在调整大小函数上方)并进行检查。
var wasResized = false;
Set it to true when resizing and add a check to you condition if it is true/false. 调整大小时将其设置为true,并在条件为true / false时添加检查。
Use a global variable to store the state 使用全局变量存储状态
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
}
}
});
You can try like this, 你可以这样尝试
$(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;
}
}
});
You could do something like this, have a counter on function execution using a closure and proceed as you need. 您可以执行类似的操作,使用闭包对函数执行进行计数,然后根据需要进行操作。
$(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.