强制代码在javascript中执行一次
我有一个特殊的场景。我有一个即时函数,在加载时在每个页面上执行强制代码在javascript中执行一次,javascript,Javascript,我有一个特殊的场景。我有一个即时函数,在加载时在每个页面上执行 (function () { if (readcookie(login)) { //i need to make it execute only once document.head.appendChild(iframe); } else { //nothing } }()); 是否可以只执行一次if语句,我无法修改登录cookie。另外
(function () {
if (readcookie(login)) { //i need to make it execute only once
document.head.appendChild(iframe);
} else {
//nothing
}
}());
是否可以只执行一次if语句,我无法修改登录cookie。另外,我不想使用全局变量或新cookie 您可以使用来记住代码是否已在上一页加载中执行:
(function () {
// Check that your custom storage variable is not set.
if (!sessionStorage.frameAppended) {
// If this is the first time the code is executed,
// create a boolean variable in the storage.
sessionStorage.frameAppended = true;
// Add the code that needs to be executed only once below this point.
if (readcookie(login)) {
document.head.appendChild(iframe);
}
}
}());
如果您希望将自定义数据永久存储(而不是按浏览器会话存储),可以使用。您能否将问题表达得更清楚一点?目前很难弄清楚你想做什么,你的问题是什么,你问什么还不清楚。它只会执行一次,至少在你通过加载一个新页面重新运行整个程序之前是这样的。“另外,我不想使用全局变量或新的cookie”:这几乎就像说:我需要记住一些东西,但不想使用内存。这闻起来像是一个错误。代码的作用是什么?为什么您希望它“只运行一次”?为什么排除Cookie和global作为解决方案?请注意,清除浏览器数据时,即使是
localStorage
,代码也会被清除,然后再次运行。@Xotic750这是真的,但没有办法解决这个问题,任何其他方法都不行。是的,这是真的。会话cookie也会起作用。我希望在浏览器会话过期时将其删除。我是这样做的:-if(readcookie(login)&&&!readcookie(frameAppended)){document.head.appendechild(iframe);创建会话cookie“frame appended”;}