在dom就绪时,从<img>'s,并在src属性中设置它们
On dom ready, get all data-src from <img>'s and set them in the src attribute
在一个页面中,我有这个:
<figure><img src="" data-src="img1.png"></figure>
<figure><img src="" data-src="img2.png"></figure>
<figure><img src="" data-src="img3.png"></figure>
<figure><img src="" data-src="img4.png"></figure>
然后继续。
我正在尝试在不使用jquery插件的情况下进行异步加载,并使其尽可能简单。
所以我想,当dom准备好并且页面完全加载时,将数据src设置为src。
如果我这样做:console.log($('figure img').attr('data-src'))
,我只得到第一个图像。所以它给了我结果:img1.png
那么,我怎么能说,当dom准备好将所有的图>img>数据src设置为该img的src时
因此:
<figure><img src="" data-src="img1.png"></figure>
<figure><img src="" data-src="img2.png"></figure>
<figure><img src="" data-src="img3.png"></figure>
<figure><img src="" data-src="img4.png"></figure>
到此:
<figure><img src="img1.png"></figure>
<figure><img src="img2.png"></figure>
<figure><img src="img3.png"></figure>
<figure><img src="img4.png"></figure>
从1.4.3版本开始,jQuery就直接理解了"data-"属性。所以就这么做吧:
$('figure img').each(function() {
this.src = $(this).data('src');
});
您必须使用.each()
来分离对最初选择的列表中每个元素的处理,以便执行的操作可以单独使用该元素。
$('figure > img').prop('src',function() {
return $(this).attr('data-src');
});
或者使用getAttribute()
会更快一点。
$('figure > img').prop('src',function() {
return this.getAttribute('data-src');
});
如果您真的想删除data-src
,那么将.removeAttr('data-src')
链接到底。
$('figure > img').prop('src',function() {
return this.getAttribute('data-src');
}).removeAttr('data-src');
相关文章:
- //而不是在src=“”上使用http://"属性
- 从其他元素上的单击事件访问image src属性
- 使用json数据更改视频标签中的src属性
- 为什么html src属性中的相对url是因为Javascript函数中的完整路径
- 无法在
标记 SRC 属性中传递参数
- 可以't将属性src设置为null,即使DOM已准备就绪
- 未捕获的类型错误:无法为 ImageButton 设置属性 'src' 的 null
- 未捕获的类型错误: 无法读取未定义的属性“src”
- JS.检查输入属性src是否包含文本
- 当属性src为null或为空时,.prp('src')为什么返回错误的值
- 不能设置属性'src'零
- 未捕获的类型错误:不能设置属性'src'当想要切换图像时为null
- 使用jQuery获取多属性(Src)
- Javascript数组问题:无法读取属性'src'的定义
- 未捕获的类型错误:不能设置属性'src'的定义
- 不能设置属性'src'JavaScript中的null
- 未捕获的类型错误:不能设置属性'src'null图像库
- 属性“src"在左边的图像上包含0
- 来自 W3C 验证程序的错误“元素脚本不得具有属性延迟,除非还指定了属性 src”
- 未捕获的类型错误:无法设置未定义的幻灯片的属性“src”