javascript:window.close();在X秒之后

时间:2013-12-11 20:27:10

标签: javascript jquery onclick settimeout

当按下提交按钮时,我弹出一个onclick动作来关闭该框:

<input type="submit" name="submit" value="submit" onclick="javascript: window.close();">

我正在尝试将其调整为在单击提交按钮关闭后等待3秒。

我读了一篇建议在:

中使用它的文章
<script> 
setTimeout("window.close()",3000) 
</script>

但无论是否点击该按钮,它都会在3秒后关闭弹出窗口。

如何使其适应按钮?

4 个答案:

答案 0 :(得分:3)

尝试组合所有内容:

<input type="submit" name="submit" value="submit" onclick="setTimeout('window.close()',3000);">

答案 1 :(得分:2)

您的第一个版本以书面形式工作

<input type="submit" name="submit" value="submit" onclick="javascript: window.close();">

因为它会在点击时关闭窗口。

您的第二个版本按书面形式工作。但你似乎有点困惑所以让我解释一下。

<script> 
 setTimeout("window.close()",3000) 
</script>

当你的html文件中内联它时,它会在视图渲染时到达时执行。执行时,此代码表示从字符串参数构造一个新函数,然后在3000毫秒内调用它。

它与任何东西无关,它只是在渲染引擎遇到它时运行。

为了将其与某些内容联系起来(而不仅仅是将其放在元素上的快捷方式,如第一个版本所示),您将需要一个事件。在javascript中,此事件将是click事件。要访问click事件,您需要在要处理事件的元素上放置clickeventhandler。并且为了能够访问元素,您必须在加载DOM时查询页面。

querySelectorAll documentation

<script>
window.onload = function(){ //this line of code will wait for the DOM to load
 //once loaded, it will execute the "anonymous" function which is the code here

 //now in here we can find the element
 //since there is no id or class, we can look for an input with name=submit
 var submitInput = document.querySelectorAll("input[name=submit]")[0];

 //once the element is found, we can attach the handler to it
 submitInput.onclick = function(){ //once again this "anonymous" function executes when the event fires
  //in here you can execute the timeout
  //lets use an anonymous function instead of constructing one from a string
  setTimeout(function(){
   window.close();
  },3000);
 };
};
</script>

执行此操作后,您可以从元素

中删除onclick事件处理程序
<input type="submit" name="submit" value="submit" />

你有它,这是适合你情况的最佳实践方法。

的jQuery

如果你设置使用jQuery来执行此操作,则可以使用document.ready功能的快捷方式(如等待所有元素可用),然后在该快捷方式的回调中,您将定位元素(在jQuery中你使用css-ish选择器),然后告诉jQuery注册click事件,这涉及另一个回调函数。

看起来像这样:

<script>
 $(function(){//document.ready shortcut
  $("input[name=submit]").click(function(){//target element and request click event
   setTimeout(function(){window.close();},3000);//timeout code to close window
  });
 });
</script>

答案 2 :(得分:0)

尝试:

<input type="submit" name="submit" value="submit" onclick="closeWindow()">

然后在Javascript上添加如下函数:

function closeWindow(){
    setTimeout("window.close()", 3000);
}

未经测试,但应该可以使用。

答案 3 :(得分:0)

这对我来说效果很好:

sqldf("explain query plan select a.id, zipcode, b.pct
      from df1 a left join df2 b using(zipcode)
      where [exp.id] = 0")
##   id parent notused                                                           detail
## 1  3      0       0                                              SCAN TABLE df1 AS a
## 2 16      0       0 SEARCH TABLE df2 AS b USING AUTOMATIC COVERING INDEX (zipcode=?)