Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在新创建的窗口中进行div_Javascript_Object - Fatal编程技术网

Javascript 在新创建的窗口中进行div

Javascript 在新创建的窗口中进行div,javascript,object,Javascript,Object,我制作了一个计时器,显示我新创建的窗口 但是,它每次都重复文本,因为我写了一行新词 我想在窗口中创建一个div元素,以便每秒替换(更新)文本 对象: venster = window.open('new.html','titel','width=500, height= 500'); 我的计时器: function stopwatch(sec){ //timer venster.document.write("window closes in: " + sec); i

我制作了一个计时器,显示我新创建的窗口

但是,它每次都重复文本,因为我写了一行新词

我想在窗口中创建一个div元素,以便每秒替换(更新)文本

对象:

venster = window.open('new.html','titel','width=500, height= 500');
我的计时器:

function stopwatch(sec){
    //timer 
    venster.document.write("window closes in: " + sec);
    if(sec < 1){
        clearTimeout(timer);
        venster.document.write("<h1>i will close!</h1>");
        //setTimeout(venster.close(),2000);
        }
    sec--;
    var timer = setTimeout('stopwatch('+sec+')',1000);
    }
功能秒表(秒){
//计时器
venster.document.write(“窗口关闭:”+秒);
如果(秒<1){
清除超时(计时器);
venster.document.write(“我会关闭!”);
//setTimeout(venster.close(),2000);
}
第二节;
var timer=setTimeout('stopwatch('+sec+'),1000);
}

我希望文本“window closes in..”只显示一次,而不是每秒显示一行新的文本。

问题在于变量
计时器
仅存在于函数范围中。当您想要清除计时器时,它没有值


在函数外部定义变量
timer

缺少
else
子句。如果你想替换整个内容,那么
innerHTML
就是你想要的<代码>文档。写入将始终只是添加

function stopwatch(sec){
    if(sec < 1){
        venster.document.body.innerHTML = "<h1>i will close!</h1>"; // Also this h1 wasn't closed
        setTimeout(venster.close ,1000); // And this was executed immediately rather than passing on a function
    } else {
        venster.document.body.innerHTML = "window closes in: " + sec;
        setTimeout(function() { stopwatch(sec-1) }, 1000); // And this would look prettier wrapped in an anonymous function
    }
}
功能秒表(秒){
如果(秒<1){
venster.document.body.innerHTML=“我将关闭!”;//此h1也未关闭
setTimeout(venster.close,1000);//这是立即执行的,而不是传递函数
}否则{
venster.document.body.innerHTML=“窗口在:”+秒内关闭;
setTimeout(function(){stopwatch(sec-1)},1000);//用匿名函数包装起来会更美观
}
}

我仍然一遍又一遍地收到相同的文本,直到我的计时器打开0Ah,等等,我看错了。我认为问题出在
h1
上,而不是
窗口在
文本中关闭
document.write
将始终添加而不是替换然后
innerHTML
就是您想要的