我知道在PHP中,你可以像一堆不同的圖像,當你離開頁面,回來或刷新它,你會得到不同的圖像。是否有可能在jQuery中做到這一點?jQuery刷新不同的圖像
對不起,我沒有測試代碼,我只是不知道從哪裏開始對這個
我知道在PHP中,你可以像一堆不同的圖像,當你離開頁面,回來或刷新它,你會得到不同的圖像。是否有可能在jQuery中做到這一點?jQuery刷新不同的圖像
對不起,我沒有測試代碼,我只是不知道從哪裏開始對這個
你可以做一些簡單的像這樣
var random = Math.floor(Math.random()*3);
if(random == 0){
$('#one').show();
}
if(random == 1){
$('#two').show();
}
if(random == 2){
$('#three').show();
}
(一次又一次地點擊運行來看到的變化,這是一樣的頁面重載,因爲這會被稱爲onLoad)
是的,這是可能的。
假設你想做一切客戶端,我認爲你有兩個選擇。一種是每次隨機顯示不同的圖片。
其次是存儲cookie並根據cookie值顯示圖像。
如果你想使用cookie方法來確保用戶永遠不會獲得相同的兩次我將所有的信息粘貼到一個json,你可以從ajax請求獲得if ne EDED。
但是,這可能是你所需要的矯枉過正!
例
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
//JSON with your image data
var imageJson = {"images": [
{"imgSrc": "image1.jpg", "imgAlt": "Image one"},
{"imgSrc": "image2.jpg", "imgAlt": "Image two"},
{"imgSrc": "image3.jpg", "imgAlt": "Image three"}
]
};
//Wait for dom to load then do our stuff
$(document).ready(function() {
moveCookie();
});
//Name off your cookie
var cookieName = "counteuoi1dff";
//Id off your image tag
var imgId = "img1";
function moveCookie(){
if(getCookie(cookieName) != undefined){
var lastImage = parseInt(getCookie(cookieName));
if(lastImage > imageJson.images.length-1){
setCookie(cookieName,0,365);
lastImage = 0;
}
$("#"+imgId).attr("src",imageJson.images[lastImage].imgSrc);
$("#"+imgId).attr("alt",imageJson.images[lastImage].imgAlt);
setCookie(cookieName,lastImage+1,365);
}else{
setCookie(cookieName,1,365);
lastImage = 1;
}
}
//Default cookie functions for javascript dont worry about these
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
</script>
</head>
<body>
<img src="image1.jpg" alt="Image one" id="img1"/>
</body>
</html>
關閉它運行的here只是保持清爽
完美的作品,但是,這是相當大的 –
完美的例子!小而高效。謝謝! –
很高興幫助@WebMaster! –