javascript - 我可以在此 if 语句中对返回的元素调用超时函数吗?

标签 javascript

我可以在此 if 语句中对返回的元素调用超时函数吗?

var data = 'some stuff';

if(data){
  return jQuery('<div class="thisDiv"></div>').html(data);  
}

我试过以下方法:

if(data){
    setTimeout(function() {
        return jQuery('<div class="thisDiv"></div>').html(data); 
    }, 100);
}

但我在控制台中收到此错误:

Uncaught TypeError: Cannot read property 'nodeType' of undefined

最佳答案

return 语句将从您传递给 setTimeout 函数的匿名函数返回,而不是包含 if 语句范围的函数.尝试将回调传递给包含 if 语句的函数,然后使用 data 作为参数调用该回调。

function delayedReturn(callback) {
  if(data) {
    setTimeout(function() {
      callback(jQuery('<div class="thisDiv"></div>').html(data)); 
    }, 100);
  }
}

关于javascript - 我可以在此 if 语句中对返回的元素调用超时函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35136178/

相关文章:

javascript - 嵌套 JSON : How to add (push) new items to an object?

javascript - 如何从 react 导航中删除默认样式?

javascript - 如何在 Selenium IDE 中验证样式属性

javascript - 在 d3 可视化中访问 MySQL 数据库

javascript - 如何在 Canvas 上制作类似powerpoint可调文本的文本?

javascript - jQuery UI 拖动 - 无法在填充区域上移动

javascript - 当类型值相等时如何禁用字段

javascript - 如何让一个元素显示在 youtube 视频前面?

javascript - 从 ES6 模块导入函数表达式或函数声明有什么区别?

javascript - 使用PHP在同一页面中计算