How to load all the images from one of my folder into my web page, using Jquery/Javascript

后端 未结 14 2179
情深已故
情深已故 2020-11-22 10:18

I have a folder named \"images\" in the same directory as my .js file. I want to load all the images from \"images\" folder into my html page using Jquery/Javascript.

<
14条回答
  •  萌比男神i
    2020-11-22 11:12

    Using Chrome, searching for the images files in links (as proposed previously) didn't work as it is generating something like:

    (...) i18nTemplate.process(document, loadTimeData);
    
    
    
    
    

    Maybe the most reliable way is to do something like this:

    var folder = "img/";
    
    $.ajax({
        url : folder,
        success: function (data) {
            var patt1 = /"([^"]*\.(jpe?g|png|gif))"/gi;     // extract "*.jpeg" or "*.jpg" or "*.png" or "*.gif"
            var result = data.match(patt1);
            result = result.map(function(el) { return el.replace(/"/g, ""); });     // remove double quotes (") surrounding filename+extension // TODO: do this at regex!
    
            var uniqueNames = [];                               // this array will help to remove duplicate images
            $.each(result, function(i, el){
                var el_url_encoded = encodeURIComponent(el);    // avoid images with same name but converted to URL encoded
                console.log("under analysis: " + el);
                if($.inArray(el, uniqueNames) === -1  &&  $.inArray(el_url_encoded, uniqueNames) === -1){
                    console.log("adding " + el_url_encoded);
                    uniqueNames.push(el_url_encoded);
                    $("#slider").append( "" );      // finaly add to HTML
                } else{   console.log(el_url_encoded + " already in!"); }
            });
        },
        error: function(xhr, textStatus, err) {
           alert('Error: here we go...');
           alert(textStatus);
           alert(err);
           alert("readyState: "+xhr.readyState+"\n xhrStatus: "+xhr.status);
           alert("responseText: "+xhr.responseText);
       }
    });

提交回复
热议问题