element $(this)在console.log中输出不同的格式

时间:2016-03-08 00:29:35

标签: javascript jquery console

我循环使用相同类名的元素并使用console.log打印元素,如下所示:

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

然而,console.log的输出是意外的,在以下格式之间随机变化:

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

首选格式是第二个完整元素输出。

以下是我的控制台的屏幕截图:

enter image description here

我认为这会导致我的程序稍后加载这些图片时出现问题,是否有人能指出我正确的修复方向?

2 个答案:

答案 0 :(得分:1)

您可以使用:

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

此处的示例:jsFiddle

答案 1 :(得分:-1)

你想在控制台打印什么?

尝试这样的事情:

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

或者也许是attr?

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

确保将其缠绕在一起,以便网站首先加载,然后循环浏览图片。

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