Dal*_*ían 2 javascript jquery onclick settimeout
当按下提交按钮时,我有一个带有 onclick 操作的弹出窗口来关闭该框:
<input type="submit" name="submit" value="submit" onclick="javascript: window.close();">
Run Code Online (Sandbox Code Playgroud)
我正在尝试将其调整为在单击提交按钮关闭后等待 3 秒。
我读过一篇文章,建议在以下内容中使用它:
<script>
setTimeout("window.close()",3000)
</script>
Run Code Online (Sandbox Code Playgroud)
但无论是否单击按钮,它都会在 3 秒后关闭弹出窗口。
我如何调整它以使用按钮?
您的第一个版本按书面方式工作
<input type="submit" name="submit" value="submit" onclick="javascript: window.close();">
Run Code Online (Sandbox Code Playgroud)
因为它会在单击时关闭窗口。
您的第二个版本按书面方式工作。但你似乎有点困惑,所以让我解释一下。
<script>
setTimeout("window.close()",3000)
</script>
Run Code Online (Sandbox Code Playgroud)
当它被内联在你的 html 文件中时,它将在视图渲染时到达它时执行。执行时,此代码表示从字符串参数构造一个新函数,然后在 3000 毫秒内调用它。
它不绑定任何东西,它只是在渲染引擎遇到它时运行。
为了将它与某些东西联系起来(而不是像第一个版本中所示,只是采取将它放在元素上的快捷方式),您将需要一个event。在 javascript 中,此事件将是点击事件。为了访问单击事件,您需要在要为其处理事件的元素上放置一个 clickeventhandler。为了访问该元素,您必须在加载 DOM 时查询该元素的页面。
<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>
Run Code Online (Sandbox Code Playgroud)
这样做之后,您可以从元素中删除 onclick 事件处理程序
<input type="submit" name="submit" value="submit" />
Run Code Online (Sandbox Code Playgroud)
这就是适合您情况的最佳实践方法。
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>
Run Code Online (Sandbox Code Playgroud)