简体   繁体   中英

element $(this) output different format in console.log

I'm looping through elements with the same class name and printing the element using console.log as follows:

$('.thumbImg').each(function(i) {
  console.log("i is", i, "this is", this);
});

However the console.log 's output is unexpected, changing at random between the following formats:

i is 13 this is img.thumbImg
i is 14 this is <img class=​"thumbImg" src=​"images/​bookcovers/​jekyllhyde.jpg" alt>​

The preferred format is the second full element output.

Here is a screenshot of my console:

在此输入图像描述

I think this is causing problems with loading these images later in my program, could anyone point me in the right direction to a fix?

You can use :

$('.thumbImg').each(function(key,element) {
alert("i is "+ key+ " this is "+ element.outerHTML);
});

An example here: jsFiddle

What are you trying to print out in the console?

Try something like this:

$('.thumbImg').each(function(i) {
    console.log("i is", i, "this is", $(this));
});

Or maybe a attr?

$('.thumbImg').each(function(i) {
    console.log("i is", i, "this is", $(this).attr('src'));
});

Make sure you have this wrapped around it so the site can load first then loop through your images.

$(document).ready(function() { 
    /* code here */ 
});

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