当按下提交按钮时,我有一个带有 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/