图像高度只会从一大组图像中检索一次



所以,就像我在标题中所写的那样,我有多个具有相同类的元素,我提取该类,并尝试检查该图像的子图像的宽度/高度/src。

我只得到了第一个图像的高度//宽度,但我得到了所有图像的src。

这是html:

<a class="test">
<img src="http://www.kitchenspro.com/files/Testimonials/Large/1502046700250312a71707.jpg">
</a>
<a class="test">
<img src="http://www.kitchenspro.com/files/Testimonials/Large/40183.9461166782.jpg">
</a>
<a class="test">
<img src="http://sphotos-a.xx.fbcdn.net/hphotos-ash4/s480x480/391362_365319466870994_1543740404_n.jpg">
</a>

这是jquery

var imagesrc= "";
var imageheight = "";
var imagewidth = "";
var i=0;
$(".test > img").each(function() {
i++;
imagesrc = $(this).attr("src");
imageheight = $(this).width();
imagewidth = $(this).height();
document.write("<br>This is image's src: " + imagesrc + " This is img height: " + imageheight + " this is width: " + imagewidth + "<br>");            
});

如果我没有以正确的方式呈现代码,我深表歉意。

如有任何帮助,我们将不胜感激。

提前感谢。

document.write的第一次调用会破坏其余元素,因此您只能从其中一个元素中获取信息,请使用.append()或其他方法来显示结果。

正是@Musa所说的。

为了帮助清理您的代码并上一堂关于效率和本地javascript的课,我提供了一个片段。

// Document Fragments are lightweight DOM containers. Append elements to this in loops and then attach the fragment to the actual DOM afterwards to increase efficiency. 
var frag = document.createDocumentFragment();
// i, or index, comes out of box in most loops.
$(".test img").each(function(i, el) {
 // Local variables specific to each image
 var imagesrc = $(this).attr("src");
 var imageheight = $(this).width();
 var imagewidth = $(this).height();
 var message = "This is image's src: " + imagesrc + " This is img height: " + imageheight + " this is width: " + imagewidth;
 // Appending the node to the frag with native js
 var p = document.createElement("p");
 p.innerText = message;
 frag.appendChild(p);
 // Viewing the console message for fun
 console.log(message);     
});
document.body.appendChild(frag);

最新更新