我前一段时间问了这个问题,并对接受的答案感到满意.然而,我刚才意识到以下技术:
var testaroo = 0;
(function executeOnLoad() {
if (testaroo++ < 5) {
setTimeout(executeOnLoad, 25);
return;
}
alert(testaroo); // alerts "6"
})();
Run Code Online (Sandbox Code Playgroud)
返回我期望的结果.如果TJCrowder从我的第一个问题的回答是正确的,那么这种技术不应该起作用吗?
我今天在IE8中遇到了一个问题(注意我只需要支持IE)我似乎无法解释:使用命名的匿名函数处理程序时detachEvent不起作用.
document.getElementById('iframeid').attachEvent("onreadystatechange", function onIframeReadyStateChange() {
if (event.srcElement.readyState != "complete") { return; }
event.srcElement.detachEvent("onreadystatechange", onIframeReadyStateChange);
// code here was running every time my iframe's readyState
// changed to "complete" instead of only the first time
});
Run Code Online (Sandbox Code Playgroud)
我最终发现改变onIframeReadyStateChange以使用arguments.callee(我通常会避免)而不是解决了这个问题:
document.getElementById('iframeid').attachEvent("onreadystatechange", function () {
if (event.srcElement.readyState != "complete") { return; }
event.srcElement.detachEvent("onreadystatechange", arguments.callee);
// code here now runs only once no matter how many times the
// iframe's readyState changes to "complete"
});
Run Code Online (Sandbox Code Playgroud)
是什么赋予了?!第一个代码段不应该正常工作吗?
javascript internet-explorer anonymous-function javascript-events