jQuery $(window).load与window.onload之间的区别 [英] Difference between Jquery $(window).load vs window.onload

查看:346
本文介绍了jQuery $(window).load与window.onload之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

function initialize() {
  var mapOptions = {
    center: new google.maps.LatLng(53.743317, -0.331004),
    zoom: 12
  };
  var map = new google.maps.Map(document.getElementById("map-canvas"),  mapOptions);
}

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?key={APIKEY}&sensor=false&callback=initialize';
  document.body.appendChild(script);
}

如果我放

$( window ).load(function() {
    loadScript;
});

它不会加载我的地​​图. Google Maps JS中的错误是Uncaught TypeError: Object #<Object> has no method 'Load'.但是,如果我使用

It won't load my map. Error in google maps js is Uncaught TypeError: Object #<Object> has no method 'Load'. However if I use

window.onload = loadScript;

它将很好地加载它.我完全不知道为什么.

It will load it in fine. I have absolutely no idea why.

$(window).load(loadScript());

也可以,只是将其作为调用它的函数而没有.你能告诉我这种现象的原因吗?

Also works, just having it as a function that calls it doesn't. Could you tell me the reason of this behavior?

推荐答案

您实际上并没有在$(window).load()版本中调用loadScript-您刚刚创建了一个"void"表达式,该表达式的计算结果为对该表达式的引用功能.

You haven't actually invoked loadScript in the $(window).load() version - you've just created a "void" expression that evaluates to a reference to that function.

执行以下任一操作

$(window).load(function() {
     loadScript();  // NB: parentheses
})

或:

$(window).load(loadScript);

也就是说,您可能希望使用$(document).ready()而不是$(window).load()

That said, you perhaps want $(document).ready() rather than $(window).load()

这篇关于jQuery $(window).load与window.onload之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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