如果您只想在页面加载时更改 div(这意味着没有为您的 div 运行幻灯片,更改您的 html 以隐藏/显示它们)
我可以考虑 3 种方法:
1)您可以尝试像以前的答案(来自@Charlie)一样使用cookies来存储当前的div。
这具有在旧浏览器中工作的优势(jquery 会处理crossbrowsing)
更新一个使用 jQuery cookie 的例子(jquery.cookie 插件)
在你的 jQuery 之后添加 jquery.cookie 插件
<script src="jquery-1.9.1.js"> </script>
<script src="jquery.cookie.js"> </script>
假设我们/你有这个 html div:
//Notice the divs are using a prefixed id with numeric ending
//(I think it's the best option)
<div id="mdiv1">
<ul><li><a href="#" id="mlink"> hello 1 </a></li></ul>
</div>
<div id="mdiv2">
<ul><li><a href="#" id="mlink"> hello 2</a></li></ul>
</div>
<div id="mdiv3">
<ul><li><a href="#" id="mlink"> hello 3</a></li></ul>
</div>
这是 jQuery 代码:
<script>
$(document).ready(function(){
//hide all divs just for the purpose of this example,
//you should have the divs hidden with your css
$('#mdiv1').hide();
$('#mdiv2').hide();
$('#mdiv3').hide();
//check if the cookie is already setted
if ($.cookie("currentDiv")===undefined){
$.cookie("currentDiv",1);
}else{ //else..well
//get and increment value, let's suppse we have just 3 divs
var numValue = parseInt($.cookie("currentDiv"));
numValue = numValue + 1;
if (numValue>3){
//restart to 1
$.cookie("currentDiv",1);
}
else{ //no issues, assign the incremented value
$.cookie("currentDiv",numValue.toString());
}
//show the div
$('#mdiv'+$.cookie("currentDiv")).show();
}
});
</script>
2) 正如@Ra Mon 评论的那样,localStorage 是另一个不错的选择(现代浏览器)来跟踪最后加载的 div。
我认为它比 cookie 更优雅,但它有一个 缺点 不能在旧浏览器上工作,当然你可以使用 Modernizer 来进行特征检测并应用一些 polyfill(使用 cookie) 进行交叉浏览。
3) 第三种方法(只要您不需要“动态”html)我想提一下的是使用服务器端会话 (php/aspx) 来跟踪最后一个div 加载/渲染并渲染下一个。如果不想使用基于内存的会话,即使您可以从服务器端处理 cookie,缺点 也会丢失缓存。
尝试一些代码并返回以使用更多和/或具体细节更新您的问题,以便有人能够帮助您,无论您选择哪种方法。
@RyanS 我的意思是:
关于“动态”如果只在页面加载时改变div,则无需使用clientSide脚本,这可以从服务器端实现。
关于“缓存”,如果您要在服务器端更改页面/html,则网络服务器将不得不再次将网页“提供”给 WebBrowser/Client,因为它从上次查看的更改(丢失缓存,添加一点负载流量,带宽使用)