[英]How to trigger a function on an element only when it has two specific classes
I have this bit of code to delay image loading by changing all 'img data-src' to 'img src'.我有这段代码可以通过将所有“img data-src”更改为“img src”来延迟图像加载。
function init() {
var imgDefer = document.getElementsByTagName('img');
for (var i=0; i<imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
} } }
window.onload = init;
At the moment it triggers when the page loads.目前它在页面加载时触发。 What I want is for it to trigger only when an element has both classes .lazy and .show
我想要的是它仅在元素同时具有 .lazy 和 .show 类时触发
The elements all look like this:所有元素都如下所示:
<li class="lazy hidden baratheon packcore" data-filtertext="01048"><a><div><img data-src="img/01048.jpg" class="cardimg"></div></a></li>
.hidden is assigned display:none, .show has display:block, and there are various clicks which will .addClass 'show' and .removeClass 'hidden'. .hidden 被分配了 display:none,.show 有 display:block,并且有各种点击将 .addClass 'show' 和 .removeClass 'hidden'。
I've played around with various combinations of我玩过各种组合
$( 'lazy, .show' ) (function () {
but I clearly understand even less than I thought I did and can't get it to work.但我清楚地理解甚至比我想象的还要少,无法让它发挥作用。
How do I trigger a function when an element exists with two specific classes - and apply the function only to those elements?当一个元素存在两个特定类时,如何触发函数 - 并将该函数仅应用于这些元素?
And is it better to have this as a separate script always looking for those two classes, or to include it in the .addclass 'show' scripts so it automatically runs when .show is added?最好将它作为一个单独的脚本来寻找这两个类,还是将它包含在 .addclass 'show' 脚本中以便在添加 .show 时自动运行?
edit: corrected the li code to show data-src instead of just src编辑:更正了 li 代码以显示 data-src 而不仅仅是 src
Checking the classes..检查类..
window.addEventListener("DOMContentLoaded",f); function f(){ var i = document.body.childNodes; for(var k=0;k < i.length; k++){ var e = i[k]; if(typeof e.className === 'undefined') continue; if((e.className.indexOf("a") > -1) && (e.className.indexOf("b") > -1)) { e.style.backgroundColor = "red"; } } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <input type="text" class="a" placeholder="Only a class"> <input type="text" class="ab" placeholder="a class and b class"> </body> </html>
Use the jQuery each() function to iterate through your .lazy.show listitems.使用 jQuery each() 函数遍历您的 .lazy.show 列表项。 Then for each one, find the child image and set src to value in data-src:
然后对于每一个,找到子图像并将 src 设置为 data-src 中的值:
$(".lazy.show").each(function(idx){
var $img = $(this).find("img");
var src = $img.data("src");
$img.prop("src", src);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.