仅使用javascript / jquery更改图像扩展名?

时间:2013-03-15 16:19:31

标签: javascript jquery

我正在制作一个简单的滑块来展示我的朋友的艺术品。我真的只熟悉javascript / jquery,所以我现在不能100%使用别的东西。

由于我的朋友没有任何编程知识,我试图让这个更新非常简单(即,每当她向文件夹中添加新图像时自动创建新图像)。她会将图像上传到文件夹,并且必须对它们进行编号(即1.jpg,2.jpg)。我的javascript使用for循环遍历数字(她必须在添加新图像时更新循环)并将它们插入到文件名中。但是,这限制了她只上传一种类型的文件。有没有办法只使用javascript更改扩展名?

这是我到目前为止所做的:

function callImages(){
    //create the image div
    $('.artslider').append('<div class="image"></div>');

    //create the files array
    var files = [];

    //start the loop, starting position will have to be updated as images are added
    for (i=8;i>=0;i--){

        //create the img src for a jpg img
        var imgJPG = 'arts/'+i+'.jpg';

        //find the natural width of the image after it loads to see if it actually exists
        var imgWidth = $('imgJPG').load().naturalWidth;

        //if the width is undefined, replace the jpg extension with gif
        if (imgWidth===undefined){
            var imgGIF = imgJPG.replace('jpg', 'gif');
            files[i] = '<img src="'+imgGIF+'" class="artsliderimg"/>';
        }

        //otherwise keep the jpg extension
        else {
            files[i] = '<img src="'+imgJPG+'" class="artsliderimg"/>';
        }

        //then add the images to the img div
        $('.image').append(files[i]);
    }
};

这个if / else的问题在于它只会创建一个gif图像。如果您切换订单,它只会创建一个jpg图像。

编辑:这是代码生成的内容:https://googledrive.com/host/0B1lNgklCWTGwV1N5cWNlNUJqMzg/index.html

1 个答案:

答案 0 :(得分:1)

问题在于这段代码:

var imgJPG = 'arts/'+i+'.jpg';
var imgWidth = $('imgJPG').load().naturalWidth;

imgWidth将始终未定义。

首先,您传入字符串'imgJPG'而不是参数imgJPG。其次我认为你误解了jQuery选择器,这用于选择HTML元素,输入文件路径到这里将无法实现任何目标。第三,我认为你误解了load函数,它用于将数据从服务器加载到HTML元素中。

我建议使用下面的函数来检查图像是否存在:

function urlExists(url) {
  var http = jQuery.ajax({
    type:"HEAD",
    url: url,
    async: false
  });
  return http.status == 200;
}

然后在你的代码中:

if (!urlExists(imgJPG)){
    var imgGIF = imgJPG.replace('jpg', 'gif');
    files[i] = '<img src="'+imgGIF+'" class="artsliderimg"/>';
}
else {
    files[i] = '<img src="'+imgJPG+'" class="artsliderimg"/>';
}