为什么 jQuery 的 load 事件不会在动态插入的脚本元素上触发?

2024-03-29

我使用 jQuery 动态插入脚本元素。脚本按预期加载,但加载事件未触发。

jQuery('<script/>').attr({
    type : 'text/javascript',
    src : 'http://platform.twitter.com/widgets.js'
}).appendTo('body').load(function(){
    /* This alert does not fire: */
    alert('I just loaded!');
});

如果我使用常规 JavaScript 插入元素,则 load 事件会触发并且可以用 jQuery 捕获。

var e = document.createElement('script'); 
e.type = 'text/javascript';
e.src = 'http://platform.twitter.com/widgets.js';
document.body.appendChild(e);

jQuery(e).load(function(){
    /* This alert does fire: */
    alert('I just loaded!');
});

我究竟做错了什么?


Use the jQuery.getScript()[docs] http://api.jquery.com/jQuery.getScript/ method instead.

$.getScript('http://platform.twitter.com/widgets.js',function(){
    alert('I just loaded!');
});

或者,在当前版本的 jQuery 上,使用如下的 Promise 模式

$.getScript('http://platform.twitter.com/widgets.js')
  .done(function(){
    alert('I just loaded!');
  })
  .fail(function(){
    console.log('script could not load');
  })
;

EDIT:删除了从问题中复制的代码注释,因为它增加了答案的混乱。谢谢@Jeff https://stackoverflow.com/users/561545/jeff指出这一点。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 jQuery 的 load 事件不会在动态插入的脚本元素上触发? 的相关文章

随机推荐