【问题标题】:$.when($("").function() == true).then() not working as expected$.when($("").function() == true).then() 没有按预期工作
【发布时间】:2017-08-24 18:01:30
【问题描述】:

我有一个返回真或假的函数。现在我想在函数返回“true”后执行一些代码。

该函数确定元素是否在屏幕上可见。我是从here 拿来的。

元素在页面加载后 1-2 秒显示。但由于这也与用户的互联网连接有关,我不想使用 setTimout 函数。 我尝试了一些事情并发现它在 if/else 语句中有效,但在 when/then 中无效。任何想法,这里出了什么问题?

我测试了一些东西,见下面的代码

//below if else statement works fine and logs the correct result
    if($(".myClass").isOnScreen()==true){
        console.log("true");
    }
    else{console.log("false");}

//however i would like to use this one and it doesn't seem to work
$.when($(".myClass").isOnScreen()==true).then(function(){
    console.log($(".myClass").isOnScreen());
    setTimeout(function(){
        console.log($(".myClass").isOnScreen());
    },1000);
});

when / then 语句的实际作用: 只要函数 isOnScreen 运行,它就会运行,但不会等到返回响应为真。因此控制台日志总是错误的。 然后我实现了一个超时(仅用于测试目的)。在timeOut跑完之后,控制台日志一直是假的。

它应该做什么: 当结果为真后,应该运行when/语句。

【问题讨论】:

  • isOnScreen 看起来像一个 sync 操作,如果你将它包装在承诺/超时中,你最终会出现不一致的行为......
  • 您链接到的逻辑设计为在scroll 事件处理程序中使用。它不返回承诺,也不应该与一个承诺一起使用

标签: javascript jquery return-value when-js


【解决方案1】:

您链接到的逻辑设计为在scroll 事件处理程序中使用。它不返回一个承诺,也不应该与一个承诺一起使用。

要解决您的问题,请使用如下插件:

$.fn.isOnScreen = function() {
  var element = this.get(0);
  var bounds = element.getBoundingClientRect();
  return bounds.top < window.innerHeight && bounds.bottom > 0;
}
var $output = $('.output'), $foo = $('.foo');

// the important part:
$(window).on('scroll', function() {
  $output.text('visible: ' + $foo.isOnScreen());
});
.box {
  width: 50px;
  height: 50px;
  margin: 10px;
  background-color: #CCC;
}

.foo {
  background-color: #C00;
}

.output {
  position: fixed;
  top: 50px;
  right: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box foo"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

<div class="output"></div>

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2020-03-18
    相关资源
    最近更新 更多