javascript - 如何在 X 秒后应用 window.close()?

标签 javascript jquery onclick settimeout

当按下提交按钮时,我有一个带有 onclick Action 的弹出窗口来关闭框:

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

我试图让它在点击提交按钮关闭后等待 3 秒。

我读了一篇文章,建议在 :

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

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

如何调整它以与按钮一起使用?

最佳答案

您的第一个版本按书面形式运行

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

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

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

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

当它内联到您的 html 文件中时,它将在 View 呈现时到达时执行。执行时,这段代码表示从字符串参数构造一个新函数,然后在 3000 毫秒后调用它。

它不依赖于任何东西,它只在渲染引擎遇到它时运行。

为了将它与某些东西联系起来(而不是像第一个版本中所示那样只是采用将它放置在元素上的快捷方式),您将需要一个事件。在 javascript 中,此事件将是点击事件。为了访问点击事件,您需要在您希望为其处理事件的元素上放置一个 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 注册点击事件,这涉及另一个回调函数。

看起来像这样:

<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>

关于javascript - 如何在 X 秒后应用 window.close()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20529245/

相关文章:

jquery - 选择的搜索不适用于 Jquery 对话框。为什么?

javascript - Node.js 循环和 JSON 构建

html - 按钮在 Chrome 中不起作用

javascript - CSS :When i click in one element two was clicked

javascript - 如何创建类似 Vultr.com 的用户界面演示

javascript - 无限滚动重复ajax调用

javascript - 延迟一段时间后显示第二个 div,如果鼠标悬停在第一个或第二个 div 上,则保持第二个 div 可见

javascript - 如何使用 javascript 将数字添加到 onclick url

javascript - 无法在模板重复 polymer 内调用核心折叠切换

javascript - React Native 中的条件导入