为什么在DOM准备好后我的函数没有被调用?

时间:2015-08-11 20:46:19

标签: javascript jquery dom responsive-design

有人可以向我解释为什么在我定义它之后尝试调用它的行上没有调用下面的rescaleStuff函数吗?

jQuery(function ($) { // $(document).ready equivalent

    function scaleStuff()
    {
        // make elements with class 'same-height-as-width' have the self-explanatory property
        $('.same-height-as-width').each(function () {
            var thisElement = $(this);
            thisElement.height(thisElement.width());
        });

        // make font size of carousel proportional to height 
        var factor = 15; // factor to scale the font size, e.g. factor=15 means font-size of the outer div
                         // if 1/15 of its height. The descendant text elements have font-size defined in em
        $('#front-page-carousel-blue-strip').css('font-size', ($('#front-page-carousel-blue-strip').height() / factor).toString() + 'px');
    }

    scaleStuff(); // scale on page load

    // ... bunch of other stuff 

}

在加载页面后,我不必调整窗口大小以使所有内容立即扩展。

4 个答案:

答案 0 :(得分:4)

我想你真的想要:

$(document).ready(function() {
  ...
})

$(function() {
   ...
})

请注意,$jQuery互换的任何组合均有效。

答案 1 :(得分:2)

你有什么好。您在声明后错过了结束)

jQuery(function ($) { // $(document).ready equivalent

    function scaleStuff()
    {
        // make elements with class 'same-height-as-width' have the self-explanatory property
        $('.same-height-as-width').each(function () {
            var thisElement = $(this);
            thisElement.height(thisElement.width());
        });

        // make font size of carousel proportional to height 
        var factor = 15; // factor to scale the font size, e.g. factor=15 means font-size of the outer div
                         // if 1/15 of its height. The descendant text elements have font-size defined in em
        $('#front-page-carousel-blue-strip').css('font-size', ($('#front-page-carousel-blue-strip').height() / factor).toString() + 'px');
    }

    scaleStuff(); // scale on page load

    // ... bunch of other stuff 

}    /* <-- Missing the closing ")". */

请记住}关闭作为参数传递的函数。 )关闭jQuery(...)函数调用。一旦你添加它,它应该工作正常。我使用您的语法模拟了下面的示例,以证明这确实有效:

&#13;
&#13;
jQuery(function ($) {
  alert($().jquery);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

尝试使用 jQuery(document).ready(function( $ ) { ... });

答案 3 :(得分:0)

看看这里:https://learn.jquery.com/using-jquery-core/document-ready/

$( document ).ready(function() {
    console.log( "ready!" );
});

$(function() {
    console.log( "ready!" );
});

// Passing a named function instead of an anonymous function.

function readyFn( jQuery ) {
    // Code to run when the document is ready.
}

$( document ).ready( readyFn );
// or:
$( window ).load( readyFn );