<html>
<script type="text/javascript">
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 executeFunc() {
var cookieData=document.cookie.split(';');
for(entry in cookieData)
{
createCookie(cookieData[entry],"",-1); //clear the cookie first
}
createCookie("node-1","1",365);
createCookie("node-2","1",365);
createCookie("node-3","1",365);
alert("the cookie contains : " + document.cookie);
var cookie=document.cookie.split(';');
for(ele in cookie)
{
var node=cookie[ele].split('=');
alert(node[0]); //this prints the next node correctly
var nodeId=document.getElementById(node[0]); //for the first
//iteration i get the row in
//nodeId correctly but for the next iterations, i get null,
//althought the row exists. if i type in the row Id manually
//it works, but if i use node[0] then it returns null !! :S
alert("the node is : " + nodeId);
alert(document.cookie);
}
}
</script>
<body onLoad="executeFunc()">
<table>
<tbody>
<tr id="node-1">
<td>im node 1</td>
</tr>
<tr id="node-2">
<td>im node 2</td>
</tr>
<tr id="node-3">
<td>im node 3</td>
</tr>
</tbody>
</table>
</body>
</html>首先,我不知道如何在Jsfiddle上运行上面的代码,然后将它链接到我的问题。很抱歉!
在javascript的executeFunc()中,我拆分cookie条目并提取"node“变量中的名称。然后使用这个名称,获取行对象并打印它。当它第一次循环时,一切都按计划进行,但是对于下一次迭代,alert(node[0])打印cookie中的下一个条目(即node-2),但是nodeId=document.getElementById(node[0])返回null。如果我把它改成nodeId=document.getElementById("node-2"),它就能正常工作。我不知道prblm is..you可以通过复制粘贴it...its完整的代码来测试它!!谢谢!!
发布于 2011-07-15 05:07:38
您的cookie在每个标识符的前面都有一个空格。因此,它试图查找" node-1",但没有找到它。您可以看到此版本代码中的空格,警告文本周围有引号:http://jsfiddle.net/jfriend00/ZS3HB/。
我建议要么将拆分修改为split('; '),要么在使用标识符之前删除前导/尾随空格。
发布于 2011-07-15 05:09:46
问题是您在';'上拆分,但是每个分号后面都有一个空格,因此第二个节点名以" node-2"而不是"node-2"结尾。
如果你在'; '上拆分,它将会工作。
或者,您可以从名称中删除空格:
if (node[0].charAt(0) == ' ') {
node[0] = node[0].substr(1);
}https://stackoverflow.com/questions/6699836
复制相似问题