0

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

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

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

我的咖啡脚本:

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

编辑:

这是我的脏代码:我来自咖啡脚本的 javascript 代码

4

1 回答 1

3

这可能是由于图像尚未完成加载,因此返回的高度和宽度为 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();
});
于 2012-07-13T18:13:44.030 回答