0

我写了一个带参数的函数,我正在尝试调用该函数。但是,我不断收到“未捕获的引用错误:未定义“函数”。

这是我的代码:

var bColor, fColor, fStyle, bUrl;
jQuery(function changeBackground(bColor, fColor, fStyle, bUrl) {
    if (typeof (bColor) === 'undefined') bColor = '#fff';
    if (typeof (bUrl) === 'undefined') bUrl = '';
    if (typeof (fColor) === 'undefined') fColor = '#000';
    if (typeof (fStyle) === 'undefined') fStyle = 'Monda';
    WebFontConfig = {
        google: { families: [ fStyle ] }
    };
    (function() {
        var wf = document.createElement('script');
        wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
            '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
        wf.type = 'text/javascript';
        wf.async = 'true';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(wf, s);
    })();
    jQuery('body').css({ backgroundColor: bColor, backgroundUrl: bUrl, color: fColor, fontFamily: fStyle });
});

无论我是否从脚本运行该函数,我都会收到错误消息。或者,如果我通过任何元素调用(例如 onload)运行它。

我不知道为什么会出现错误,也许另一双眼睛可以发现我的错误。

4

1 回答 1

0

When you pass a function to the jQuery object like $(fn) it's the same as $(document).ready(fn). Your first parameter bColor is actually jQuery. What you probably want is to wrap everything in the ready event and use $ inside of that closure:

jQuery(function($){

  // use `$` from now on instead of `jQuery`

  var bColor, fColor, fStyle, bUrl;

  function changeBackground() {
    ...
  }

});
于 2013-08-07T03:41:45.947 回答