您的第一个版本按编写的方式工作
<input type="submit" name="submit" value="submit" onclick="javascript: window.close();">
因为单击时它将关闭窗口。
您的第二个版本按编写的方式工作。但你似乎有点困惑,所以让我解释一下。
<script>
setTimeout("window.close()",3000)
</script>
当它内联到您的 html 文件中时,它将在视图渲染时到达它时执行。执行时,这段代码表示从字符串参数构造一个新函数,然后在 3000 毫秒内调用它。
它不与任何东西绑定,只是在渲染引擎遇到它时运行。
为了将其与某些东西联系起来(而不仅仅是像第一个版本中所示那样采用将其放置在元素上的快捷方式),您将需要一个event。在 javascript 中,该事件将是点击事件。为了访问单击事件,您需要在要处理事件的元素上放置一个 clickeventhandler。为了访问该元素,您必须在加载 DOM 时查询页面以获取该元素。
querySelector所有文档 https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
<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>