从另一个文件调用$(document).ready(function() {...});

3
如标题所述,我尝试从另一个文件调用 $(document).ready(function() {...});。 代码片段如下:
源文件:
$(document).ready(function () {
    alert('document.ready function called!');
    // a lot of code
}

在测试文件中:

TestFile.prototype.testDocumentReadyContents = function () {
    // test code here trying to call the document.ready function
}

我还没有在这方面取得任何成功。我已经尝试过document.ready.apply(),trigger('ready'),覆盖document.ready函数...但是就是不能调用它。顺便说一下,我是在我的单元测试中调用它的。

谢谢。


你所说的“另一个文件”具体指的是什么?是另一个JS文件吗?还是IFrame?或者是Ajax请求? - Pekka
@ Pekka:源文件是.js文件。测试文件也是另一个.js文件。它们的包含在配置文件中,可以正常工作。 - BeraCim
1个回答

9

好的方式

$(document).ready(documentReady);

function documentReady() {
    alert('document.ready function called!');
    // a lot of code
}

TestFile.prototype.testDocumentReadyContents = function () {
    documentReady();
}

非正式的方法

TestFile.prototype.testDocumentReadyContents = function () {
    $.readyList[0]();
}

@ChaosPandion:我被告知,使用语法$(document).ready(function() {...});是一个相当标准的jQuery方法。因此,除非存在严重的标准违规问题,或者没有其他方法来实现它,否则我更倾向于不更改源代码。谢谢。 - BeraCim
2
好的,搞定了。我简直不敢相信我花了这么长时间来解决这个问题。 :) - ChaosPandion
这正是我一直在寻找的...“hackish Way”!非常感谢! :D - BeraCim
如果您将多个js文件包含到html中,每个文件都包含$(document).ready,那么最后一个文件将覆盖之前的documentReady函数。 - installero
@ChaosPandion 我知道这是一个非常旧的答案,但我有一个类似的问题,也许你可以给我一个解决方案 https://stackoverflow.com/q/51947392/7882685 - Jakub
@BeraCim 我知道这是旧问题,但我遇到了同样的问题并且无法解决。如果您还在这里,能否请您检查一下我的问题是否与此类似 stackoverflow.com/q/51947392/7882685 - Jakub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接