页面上的Jquery加载显示div并隐藏另一个

时间:2014-11-14 16:38:07

标签: jquery random load switch-statement refresh

我试图产生这样的效果:每次打开网站页面时都会出现div而另一个div消失,并且它们总是交替出现。 div1,div2,div1,div2 ....我设法通过随机做,如下面的代码,但我想切换每个页面加载,刷新的顺序。有人可以帮我这些吗?

jQuery("document").ready(function($){
var numRand = Math.floor(Math.random() * 2);
 switch (numRand) {
    case 0:
    $(".div1").remove();
        break;

    case 1:
    $(".div2").remove();
        break;
 }
});

1 个答案:

答案 0 :(得分:1)

你将不得不存储最后一次选择的内容。 Cookie可能是最简单的方法。

由于跨域问题,代码无法在SO上运行,但这是一个有效的jsFiddle

$(function() {
	var numRand = GetCookieValue("numRand") || 0;
	switch (numRand % 2) {
		case 0:
			$(".div1").remove();
			break;
		case 1:
			$(".div2").remove();
			break;
	}
	SetCookieValue("numRand", ++numRand);
});

function GetCookieValue(key) {
	var value = null;
	var cookieArray = document.cookie.split(';');
	for (var i = 0; i < cookieArray.length; i++) {
		var keyValuePair = cookieArray[i].split("=");
		if (keyValuePair[0] == key) {
			value = keyValuePair[1];
			break;
		}
	}
	return value;
}

function SetCookieValue(key, value) {
	document.cookie = key + "=" + value;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="div1">
  This is div1
</div>
<div class="div2">
  This is div2
</div>

相关问题