不同的javascript执行上下文的行为 [英] Behaviour of different javascript execution contexts
问题描述
有一个弹出窗口说-alert("Hi Tuhin!");
当我们将警报与以下列出的各种方法和事件一起使用时,基本区别是什么?
There is a popup say - alert("Hi Tuhin!");
What are the basic differences when we use alerts with various methods and events listed below:
- 直接在脚本标记示例
<script type="text/javascript">alert("Hi Tuhin!");</script>
中
- 在
document.addEventListener( "DOMLoaded", function(){alert("Hi Tuhin!");}, false);
之内
- 在
window.onload = function(){ alert("Hi Tuhin!"); }
内部
-
$("document").ready( function () { alert("Hi Tuhin!"); });
-
<script type="text/javascript"> window.alert("Hi Tuhin!") </script>
- Directly inside the script tag example
<script type="text/javascript">alert("Hi Tuhin!");</script>
- Within
document.addEventListener( "DOMLoaded", function(){alert("Hi Tuhin!");}, false);
- Inside
window.onload = function(){ alert("Hi Tuhin!"); }
$("document").ready( function () { alert("Hi Tuhin!"); });
<script type="text/javascript"> window.alert("Hi Tuhin!") </script>
推荐答案
嗯,这更多是关于如何/何时触发这些警报的问题.
Hmm, this is more of a question of how/when these alerts get fired.
1)这将在加载script
时发出警报,因此,只要您的代码下降得太远,便会发生错误.
1) This will alert when the script
is loaded, ergo whenever your code gets that far down.
2)不太确定您要在此处调用的是哪个,或者已弃用的document.observe('dom:loaded', function(){})
还是document.addEventListener("DOMContentLoaded", function(event){})
.我认为后者就是您所要的那个,它将在DOM加载后立即触发,而无需等待任何CSS/图像完成.
2) Not too sure which one you're trying to call here, either document.observe('dom:loaded', function(){})
which is deprecated or document.addEventListener("DOMContentLoaded", function(event){})
. The latter, which I assume is the one you meant, will fire as soon as the DOM is loaded without waiting for any CSS/images to finish.
3)window.onload
将在所有元素都加载到DOM中后触发,包括图像和其他内容.
3) window.onload
will fire after all elements have loaded in the DOM, including images and whatnot.
4)$("document).ready()
与DOMContentLoaded
相似,在DOM加载后即会触发.
4) $("document).ready()
fires similarly to DOMContentLoaded
, where it will fire as soon as the DOM is loaded.
5)window.alert()
与仅使用alert()
非常相似,但是如果您的作用域中有一个名为alert
的函数,则调用window.alert()是个好主意.
5) window.alert()
is pretty similar to using just alert()
, however calling window.alert() is a good idea if you have a function in your scope called alert
.
这篇关于不同的javascript执行上下文的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!