javascript - jQuery 加载后不运行 "if"

标签 javascript if-statement coffeescript

我的所有 js 脚本都可以工作,但这个不起作用

 $("img").each(function() {
      if ($(this).height() > 100) {
        return $(this).after("<p class='tasr'>FOTO © TASR</p>");
      }
    });

当我加载页面时,它不起作用,但是当我复制此脚本执行 chrome-console 时,它​​工作得很好。

我的 CoffeeScript :

jQuery $(document).ready -> 
    $("img").each ->
        if $(this).height() > 100
            $(this).after("<p class='tasr'>FOTO © TASR</p>")

编辑:

这是我的脏代码:My javascript code from coffeescript

最佳答案

这可能是因为图像尚未完成加载,因此返回高度和宽度 0。

您可能想在图像上使用 .load() 函数,该函数将在图像加载后触发,因此宽度和高度将大于 0。

这也可以解释为什么它在 chrome 控制台中工作,因为到那时图像就会加载。

编辑:@zzzzBov 在下面的评论中提到的值得注意的是,浏览器中的缓存通常会停止图像在标准刷新时调用加载函数。要解决这个问题,您只需要一个包含所有代码的函数,您可以在其中从 .load 函数和文档就绪函数内部调用

如果这是您的 html:

<img id="img1" src="example.jpg" />

然后您可以在脚本中编写类似的内容。请注意,这不是我的想法,因此可能略有错误。

function doStuff() {
    //I normally do a check here to see if the image width/height is 0 if it is then I dont bother
    //executing the rest

    //I do however sometimes need to do stuff when the image has not yet loaded which can be done here.

    //do stuff with the image, you could also pass parameters if needed.
}

$(document).ready(function() {
    doStuff();
});

$('#img1').load(function() {
    doStuff();
});

关于javascript - jQuery 加载后不运行 "if",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11475953/

相关文章:

javascript - CoffeeScript 出现意外缩进错误

javascript - 对于创建 DOM 树的 JavaScript 函数,传递 "container"节点参数与返回根节点背后的基本原理是什么

javascript - Service Worker 安装失败 : "cannot read property ' addAll of undefined"

javascript - 使用纯 JavaScript 删除数组中不包含值的选项

programming-languages - 哪些语言具有 while-else 类型的控制结构,它是如何工作的?

android - Appcelerator UrbanAirship 和 android(启动应用程序)

javascript - Three.js 仅从一侧增加盒子几何形状

ios - 根据 Sprite 的当前位置让 Sprite 移动到某个位置?

python - Django 查询结果与if语句比较

node.js - 在 node-csv-parser : RangeError: Maximum call stack size exceeded 中调用 node-mongodb-native