function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var username = getCookie("user");
if (username != "") {
$(".dropdown").append("<div id='uname' style='font-style: bold;'>" + username+ "</div>");
console.log(username);
} else {
window.location.replace("../index.php");
}
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
setCookie("user", "EricF", 1);
checkCookie();
&#13;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-default navbar">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Ver. 1.0.0 - Dated: 2017-01-30 </a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><div id="uname" style="font-style: bold;"></div><span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a data-toggle="tab" href="frames/help.html">Help</a></li>
<li><a data-toggle="tab" href="frames/about.html">About</a></li>
<li><a data-toggle="tab" href="#logout">Logout</a></li>
</ul>
</li>
</ul>
</nav>
&#13;
美好的一天, 通过cookie设置用户名的过程,我想在导航栏中显示用户名(使用Bootstrap)。 我将此代码放入导航栏:
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Ver. 1.0.0 - Dated: 2017-01-30 </a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
<div id="uname" style="font-style: bold;"></div>
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a data-toggle="tab" href="frames/help.html">Help</a></li>
<li><a data-toggle="tab" href="frames/about.html">About</a></li>
<li><a data-toggle="tab" href="#logout">Logout</a></li>
</ul>
</li>
</ul>
在Javascript(jQuery)中,我有这个:
function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var username = getCookie("user");
if (username != "") {
$("#uname").text(username);
console.log(username);
} else {
// Redirect to login
window.location.replace("../index.php");
}
}
checkCookie();
我尝试在空<div id="uname" style="font-style: bold;"></div>
之间插入用户名,但它没有显示......而且,是的,控制台为我提供了用户名!
有人可以帮忙吗?在此先感谢:)