开发者

jquery each and onload problem

开发者 https://www.devze.com 2023-01-13 21:40 出处:网络
I have this following code $(function () { $.post(\"fetch_data.php?url=\"+$(\'#url\').val(), { }, function(response){

I have this following code

$(function () {
    $.post("fetch_data.php?url="+$('#url').val(), { }, function(response){
        var arrValues = [ "path/to/img1", "path/to/img2", "path/to/img3", "path/to/img4" ]; //output from php
        var img = new Image();
        $.each(arrValues, function( intIndex, objValue ) {
            img.src = objValue;
            img.onload = function() {
            alert('height: ' + img.height + ' width: ' + img.width);
            }
        });
    });
});

I am ne开发者_开发技巧w in javascript/jquery, this code only return last("path/to/img4") height/width of image.

How do i make it return all image and width of the array?


I guess you have to create four image Elements... you have to modify your code a bit

try the bellow code,

$(function () {
    $.post("fetch_data.php?url="+$('#url').val(), { }, function(response){
        var arrValues = [ "path/to/img1", "path/to/img2", "path/to/img3", "path/to/img4" ]; //output from php

        $.each(arrValues, function( intIndex, objValue ) {
        var img = new Image(); //creating number of Image Elements equal to arrValues length
            img.src = objValue;
            img.onload = function() {
            alert('height: ' + img.height + ' width: ' + img.width);
            }
        });
    });
});


As the parameter img is defined outside your loop, it will only point to the last img u create..

try to declare the img inside the $.each loop...

and replace the img with this in the alert..

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号