jQuery不运行“;如果“;加载后

jQuery do not run "if" after load

本文关键字:加载 如果 jQuery 运行      更新时间:2023-09-26

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

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

当我加载页面时,它不工作,但当我复制这个脚本做chrome控制台时,它工作得很完美。

我的咖啡脚本:

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

编辑:

这是我的脏代码:来自coffeescript 的javascript代码

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

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

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

EDIT:@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();
});
相关文章: