当人们输入我的网址时,我希望他们点击北卡罗来纳州或弗吉尼亚州。点击后,它会将它们重定向到www.myurl.com/nc或www.myurl.com/va。在他们回答了这个问题后,下次他们访问我的网站时,会将其重定向到相应的页面,而无需再次点击NC或VA。我的链接正在工作(带我到正确的页面)但是当我返回时,cookie不会重定向我,我将返回到我要求选择状态的同一页面。这是我到目前为止所得到的。我觉得我很亲密,但老实说,我不知道我在做什么。
<p> Please tell us where you live so we can give you information for your location. </p>
<a href="#" onClick="window.location = 'http://www.myurl.com/nc'" value="nc">North Carolina</a><br />
<br />
<a href="#" onClick="window.location = 'http://www.myurl.com/va'" value="va">Virginia</a>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
function redirect(state) { createCookie('state', state, 90); window.location.href = "http://www.myurl.com/" + nc; }
</script>
我也将此脚本放在一个单独的文件中:
// JavaScript Document
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
答案 0 :(得分:0)
试试这个:
<p> Please tell us where you live so we can give you information for your location. </p>
<a href="#" onClick="redirect('nc');return false" >North Carolina</a><br />
<br />
<a href="#" onClick="redirect('va');return false" >Virginia</a>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
function redirect(state) {
createCookie('state', state, 90);
window.location.href = "http://www.myurl.com/" + state;
}
var cookie = readCookie('state');
if (cookie != null) {
window.location.href = "http://www.myurl.com/" + cookie;
}
</script>
jsfiddle:http://jsfiddle.net/7j8pG/1/