我試圖從一個頁面抓取圖片的來源網址,並在另一頁中使用它們的一些JavaScript。我知道如何使用JQuery .load()來插入圖像。然而,我不想加載所有的圖像並將它們顯示在頁面上,而是想抓取源URL,以便在JS數組中使用它們。
1僅僅是一個圖片頁面:
<html>
<head>
</head>
<body>
<img id="image0" src="image0.jpg" />
<img id="image1" src="image1.jpg" />
<img id="image2" src="image2.jpg" />
<img id="image3" src="image3.jpg" />
</body>
</html>
第2頁包含我的JS。 (請注意,最終目標是將圖像加載到數組中,隨機化它們,並使用cookie,每10秒在頁面加載時顯示一個新圖像,所有這些工作都正常,但不是將圖像路徑硬編碼到JavaScript中如下圖所示,我更願意採取基於其ID 1的路徑。通過這種方式,圖像不會總是需要名爲「image1.jpg」等)
<script type = "text/javascript">
var days = 730;
var rotator = new Object();
var currentTime = new Date();
var currentMilli = currentTime.getTime();
var images = [], index = 0;
images[0] = "image0.jpg";
images[1] = "image1.jpg";
images[2] = "image2.jpg";
images[3] = "image3.jpg";
rotator.getCookie = function(Name) {
var re = new RegExp(Name+"=[^;]+", "i");
if (document.cookie.match(re))
return document.cookie.match(re)[0].split("=")[1];
return'';
}
rotator.setCookie = function(name, value, days) {
var expireDate = new Date();
var expstring = expireDate.setDate(expireDate.getDate()+parseInt(days));
document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
}
rotator.randomize = function() {
index = Math.floor(Math.random() * images.length);
randomImageSrc = images[index];
}
rotator.check = function() {
if (rotator.getCookie("randomImage") == "") {
rotator.randomize();
document.write("<img src=" + randomImageSrc + ">");
rotator.setCookie("randomImage", randomImageSrc, days);
rotator.setCookie("timeClock", currentMilli, days);
}
else {
var writtenTime = parseInt(rotator.getCookie("timeClock"),10);
if (currentMilli > writtenTime + 10000) {
rotator.randomize();
var writtenImage = rotator.getCookie("randomImage")
while (randomImageSrc == writtenImage) {
rotator.randomize();
}
document.write("<img src=" + randomImageSrc + ">");
rotator.setCookie("randomImage", randomImageSrc, days);
rotator.setCookie("timeClock", currentMilli, days);
}
else {
var writtenImage = rotator.getCookie("randomImage")
document.write("<img src=" + writtenImage + ">");
}
}
}
rotator.check()
</script>
燦任何人都指向正確的方向?我的直覺是使用JQuery .get(),但到目前爲止我一直沒有成功。
請讓我知道,如果我可以澄清!
您不能使用get()函數與純html作爲目標。 – Radi
感謝您的幫助。我還沒有嘗試過太多與不用彷徨 - 只是爲了看看我是否可以從另一個網頁挑出IMG SRC: $獲得(「page1.html」,函數(數據){ \t \t \t \t VAR imageonly = $(數據).attr( 「SRC」);。 \t \t \t $( '結果')HTML(imageonly); \t \t \t}); 但是這真的離我想要的還有很遠,就是將它加載到上面的JS中。對不起,我對JS/JQ很陌生。 – SDD
您有使用cookies的原因嗎?爲什麼不使用'setInterval'? – saml