除非使用调整大小或单击功能,否则不会加载函数


Function is not being loaded unless resize or click function is used

我想执行一个在脚本开头定义的函数,让我们调用这个函数初始化。这个函数也使用了一个变量,我们称之为login,它是由一个php文件定义的,该文件在定义变量login后包含了我的jquery脚本文件。

php/html:

<script type="text/javascript">
login           = '<?php echo $login; ?>';
...
</script>
<!-- script is included -->
<script type="text/javascript" src="script.js"></script>

jquery:

function initialize(){
    $("." + login).remove();
}
jQuery.moreContent = function moreContent()
{
    //more content is loaded
    ...
    initialize();
}
然后加载更多内容

函数,我可以看到屏幕上出现更多内容,但没有加载初始化。 只有当我使用像 resize 这样的函数(在脚本的末尾.js文件)它才有效

jquery(在脚本末尾):

//load function initialize
initialize();
//this function doesnt work too, I tested if it even loads and it does (used a number that was increased by one whenever function was loaded which actually happened...)
//however the wished element with the class of variable login is not removed
//resize function
$(window).resize(initialize);
//this one suddenly works 
...

我不知道为什么它突然与其他功能一起使用,为什么在其他情况下

不起作用

您需要包装代码并在文档准备就绪后使其运行,如下所示:

$(document).ready (function(){
    // run all your functions here
});

也许变量 login 在另一个函数中为空,或者您正在为 thst 提供不同的值。

尝试使用全局变量进行测试,例如

window.login = script_php

再试一次,这样,login 变量是全局的,或者将此变量作为函数中的参数传递。

然后加载更多内容

函数,我可以看到屏幕上出现更多内容,但没有加载初始化。

事实并非如此。您已将函数作为方法直接附加到对象jQuery但没有调用它

jQuery.moreContent = function moreContent()
{
    //more content is loaded
    ...
    initialize();
}

这样做不会得到任何富有成效的好处。您刚刚向尚未调用的object(在本例中为 jQuery)中添加了一个方法。在任何情况下,您都不需要将其添加为jQuery对象本身的方法。您无需此操作即可轻松完成此操作,如下所示。

function initialize(){
    $("." + login).remove();
}
// this is a global function right now, use it anywhere you want.
function moreContent()
{
    //more content is loaded
    ...
    initialize();
}
// document ready...
$(function(){
    moreContent();
});

您可以重新排列代码并删除不必要的function层(取决于您的代码结构)并像这样使用它。

$(function(){
    // more content...
    initialize();
});

如果我使用像调整大小这样的函数(在脚本的末尾.js文件),它可以工作

它之所以有效,是因为它由jQuery直接附加到window resize事件。

$(window).resize(function(){
    // The code inside will work whenever user resizes the window.
    // It does not need to be hooked up inside document ready.
});

我不知道为什么它突然与其他功能一起使用,为什么在其他情况下

不起作用

它在事件处理程序中工作的原因是,您将函数挂接到以作为回调函数运行。您已clickresize事件中正确设置了它,但未load事件中设置。如果您刚刚创建了一个函数load并将其添加为jQuery对象的方法,但没有调用它。函数在 JavaScript 中运行的唯一方式是后缀括号。

function demo()
{
    // do something...
    return "Done";
}
// a named function "demo" got created, but not invoked.
demo;  // returns the whole function literal, not invoked yet.
demo(); // invoked, returns Done

因此,继续从此开始,将其添加为jQuery的方法将不会加载它,直到您调用它,例如

jQuery.myNewMethod = function myNewMethod() {
    return "Hey there :)";
}
// jQuery loaded, but where is my method ?? (@__@)
// let's invoke it then...
jQuery.myNewMethod();  // invoked the function using parenthesis!
// returns "Hey there :)"
// Now i can see you go (^__^)