简体   繁体   中英

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'.

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

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'.

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?

edit: corrected the li code to show data-src instead of just 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. Then for each one, find the child image and set src to value in data-src:

  $(".lazy.show").each(function(idx){    
    var $img = $(this).find("img");
    var src = $img.data("src");
    $img.prop("src", src);
  });

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM