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

时间:2016-07-08 04:54:09

标签: javascript php jquery html

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

的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();
}

然后加载了更多内容功能,我可以看到更多内容出现在我的屏幕上但是没有加载initialiye。只有当我使用像resize这样的函数时(在script.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 
...

我不知道为什么它突然适用于其他功能以及为什么它在其他情况下不起作用

3 个答案:

答案 0 :(得分:0)

您需要打包代码并在文档准备好后运行它,如下所示:

.secondary-menu:focus ~ .tertiary-menu { }

答案 1 :(得分:0)

也许变量login在另一个函数中是空的,或者你给的是不同的值。

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

window.login = script_php

再次尝试,以这种方式,登录变量是全局的,或者将此变量作为函数中的参数传递。

答案 2 :(得分:0)

  

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

事实并非如此。您已将函数作为方法直接附加到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();
});
  

如果我使用像resize这样的函数(在script.js文件的末尾)它可以工作

它有效,因为它在window事件上由jQuery直接附加到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对象,但未调用它。唯一且唯一的方式function runs inside JavaScript is when you suffix parenthesis

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 (^__^)