jQuery – 在文档准备好时只隐藏可见图像(加载前)
我正在开发Chrome扩展程序,并且需要一种function,以便我希望尽快(在加载之前)获取所有可见图像,隐藏它们并设置一些属性。 我一直在尝试这个:
$(document).ready(function () { $('img:visible').each(function() { $(this).css('visibility', 'hidden'); $(this).attr('data-internalid', guid()); }); });
但是在调试时,我注意到它甚至没有遍历循环。 我在这里缺少什么?
所以,正如我在评论中提到的那样
如果元素占用文档中的空间,则认为元素是可见的。 可见元素的宽度或高度大于零。
所以,你的一个选择是使用
$(window).on('load', function() { ... });
您也可以尝试替代方案,例如以下内容。
- 为您稍后要设置属性的所有图像创建一个类。
- 设置
display:none;
到CSS中的那个特定类。 - 在加载时(查看第一个选项),设置属性然后显示这些图像,方法是删除类(推荐)或设置内联样式(不漂亮)。
希望很清楚:)
$(document).ready(function (index) { $('img:visible').each(function() { $(this).css('visibility', 'hidden'); $(this).attr('data-internalid', "test"); /*instead of guid().I think that function have some problem.Make sure it is defined or loaded properly*/ }); });
问题是你的guid()函数。这个代码在firefox和chrome上运行正常。请检查函数。如果问题没有解决,那么更新你的jquery如果它是脱机的,请提供guid()函数。
$(function(){ //$("#btn").click(function(){ $('img:visible').each(function() { $(this).css('visibility', 'hidden'); $(this).attr('data-internalid', "test"); }); // }); });
img{ width:100px; height:100px; margin:10px } span{ display:block; cursor:pointer; }
Click me
检查返回$(this)
,使用控制台日志。