不同的javascript执行上下文的行为 [英] Behaviour of different javascript execution contexts

查看:94
本文介绍了不同的javascript执行上下文的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个弹出窗口说-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:

  1. 直接在脚本标记示例<script type="text/javascript">alert("Hi Tuhin!");</script>
  2. document.addEventListener( "DOMLoaded", function(){alert("Hi Tuhin!");}, false);
  3. 之内
  4. window.onload = function(){ alert("Hi Tuhin!"); }
  5. 内部
  6. $("document").ready( function () { alert("Hi Tuhin!"); });
  7. <script type="text/javascript"> window.alert("Hi Tuhin!") </script>
  1. Directly inside the script tag example <script type="text/javascript">alert("Hi Tuhin!");</script>
  2. Within document.addEventListener( "DOMLoaded", function(){alert("Hi Tuhin!");}, false);
  3. Inside window.onload = function(){ alert("Hi Tuhin!"); }
  4. $("document").ready( function () { alert("Hi Tuhin!"); });
  5. <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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆