我的所有 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>")
编辑:
最佳答案
这可能是因为图像尚未完成加载,因此返回高度和宽度 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/