JavaScript + JSON问题:无法加载照片/ undefined.jpg

时间:2015-11-06 21:39:49

标签: javascript json

我无法在此JavaScript代码中连接我的图片名称。作为初学者,它从JSON中获取,这对我来说更难。我非常感谢任何帮助!这是我的JS:

 function log(msg){
    console.log(msg)
 }

function createImage(file, parent){
    var str = file;
    var filename = ("photos/"+filename+".jpg");
    var image = new Image();
    image.src = filename;
    image.style.width = "50px";
    image.style.height = "auto";
		
    image.onload = function(){
        log('good ' + file );	
        parent.appendChild(image); //adds the image to the page!
    }
		
    image.onerror = function(){
        log('not able to load ' + filename );	
        //parent.appendChild(image);
    }
}
 

1 个答案:

答案 0 :(得分:0)

var文件名和文件存在混淆。 ;)

function log(msg){
     console.log(msg)
}

function createImage(file, parent){
    var str = file; // unused
    var filename = ("photos/"+file+".jpg"); // filename was undefined here.
    var image = new Image();
    image.src = file;
    image.style.width = "50px";
    image.style.height = "auto";

    image.onload = function(){
        log('good ' + file );   
        parent.appendChild(image); //adds the image to the page!
    }

    image.onerror = function(){
        log('not able to load ' + filename );   
        //parent.appendChild(image);
    }
}