2017-08-03 45 views
-1

我正在嘗試使用以下代碼嘗試從設置的目錄中獲取圖像,並將其預加載。我不想將圖像加載到一個div,而是使用普通預加載到存儲器:如何使用jquery從目錄加載圖像

new Image().src = "/wp-content/themes/NCHERM_Theme/images/home4-events.jpg"; 

我是相當新的jQuery的所以尋找一些幫助來完成這一點:

window.onload = function($) { 
    var folder = "images/preload"; 

    $.ajax({ 
     url : folder, 
     success: function (data) { 
      //go through each item in folder 
      $.each(data, function(i,filename) { 
       //take each item and run into the normal preload method 
       setTimeout(function() { 
        // preload images 
        new Image().src = filename; 
       }, 1000); 
      }); 
     } 
    }); 
}; 

運行這個在WordPress我得到`403上的URL forbbiden」文件夾之前,我甚至可以測試,如果這是工作

+0

好像你重寫了$對象。將它從參數 –

+0

代替'$'刪除它嘗試jQuery,對象,$,ajax到jQuery.ajax({ – LogicBlower

+0

修復,幫助解決即時錯誤,但現在得到403禁止在文件夾url – HollerTrain

回答

-1

確保您已將<script>標籤內的jQuery參考。缺少JQuery庫。

<script src="../../jquery.min.js" type="text/javascript"></script>

供您參考:$.ajax is not a function你爲什麼歌廳403錯誤,也請通過這個鏈接

+0

是jQuery是在WordPress內動態添加的 – HollerTrain

+0

@HollerTrain現在工作正常嗎? –

+0

它被加載了整個時間,所以這裏不是問題 – HollerTrain

-1

試試這個代碼,如果它爲你工作。

window.onload = function($) { 
var folder = "images/preload"; 

$.ajax({ 
    url : folder, 
    success: function (data) { 
     //go through each item in folder 
     $.each(data, function(i,filename) { 
      //take each item and run into the normal preload method 
      setTimeout(function() { 
       // preload images 
       var $img=$("<img />",{"src":filename}); 
       $('#target_id').append($img); 
      }, 1000); 
     }); 
    } 
}); 
}; 
+0

我不同意當你試圖縮放這個腳本時,你會將數千個圖像附加到一個div中,這對我沒有任何意義。我不認爲追加到'display:none' div是正確的方法 – HollerTrain

0

您可以通過添加解決403錯誤:

選項+指標

在.htaccess文件。