Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript:$不是一个函数(但似乎是)_Javascript_Jquery_Html - Fatal编程技术网

JavaScript:$不是一个函数(但似乎是)

JavaScript:$不是一个函数(但似乎是),javascript,jquery,html,Javascript,Jquery,Html,我有一个奇怪的JavaScript问题,我无法理解 我的自定义JavaScript文件“header.js”使用jQuery。它抛出了臭名昭著的“$不是函数”错误消息,但我不明白为什么。奇怪的是,我包含了jQuery.js,而且所讨论的代码在绑定到jQuery事件方面似乎没有问题。因此,没有包含jQuery不是问题所在 header.js $(document).ready(function () { if ($(document).width() >= 768) {

我有一个奇怪的JavaScript问题,我无法理解

我的自定义JavaScript文件“header.js”使用jQuery。它抛出了臭名昭著的“$不是函数”错误消息,但我不明白为什么。奇怪的是,我包含了jQuery.js,而且所讨论的代码在绑定到jQuery事件方面似乎没有问题。因此,没有包含jQuery不是问题所在

header.js

$(document).ready(function () {
    if ($(document).width() >= 768) {
        var header = false;
        var scrollHandler = function () {
            var scrollTop = $(window).scrollTop(); // line 5 that throws the error
            // more code
        };

        //register function which is called on scroll
        $(window).scroll(scrollHandler);
    }
});
我的HTML(带有一些调试输出)

但是一旦我滚动我的控制台错误输出显示:

TypeError: $ is not a function (line 5 in header.js)

有人知道这是为什么吗?我已经分析了好几个小时了,我不明白原因。任何帮助/想法/建议都将不胜感激。谢谢。

我可能有一个解决办法。这不是你想要的确切答案。但是,您可以检查将滚动处理程序的定义放在DocumentReady之外是否适合您吗? 请尝试以下方法:

var scrollHandler = function() {
    var scrollTop = $(window).scrollTop(); // line 5 that throws the error
    // more code
};

$(document).ready(function() {
    if ($(document).width() >= 768) {
        var header = false;
        //register function which is called on scroll
        $(window).scroll(scrollHandler);
    }
});

如果这也不起作用,那么有一些内容覆盖了$definition。你能告诉我们这在你的代码中是否有效吗?

好的,如果你有同样的问题,这里是我如何解决的

问题是与require.js冲突。Require.js在Sitecore中自动附带一个模块。起初,我不知道require.js导致了这种冲突,因为当我检查JavaScript文件时,我正在寻找对$的覆盖。此时我不知道的是require.js还有一个配置文件,其中包含自己版本的jQuery


我通过删除require.js(并将它手动带来的依赖项添加到我的页面)解决了这个问题。

为什么使用
“~/js/vendor/jquery.js”
而不是
”/js/vendor/jquery.js“
”/js/vendor/jquery.js?”
?这里唯一真正的可能性是,在主页加载完成后,您正在将包含的内容分配给
$
。因此,您需要找到它并…停止它这样做。
~
表示UNIX系统中的主目录。没关系,这不是一个错误的代码。@MarcosPérezGude:如果文件是从服务器加载的,那就是。如果从
file://
加载它也没关系(但这样做通常是处理网页的糟糕方式,浏览器使用
file://
页面与从服务器加载的页面做的事情略有不同)。当然,据我们所知,OP有一个服务器配置为能够理解相对URL中的
~
。发布第二次
printTest()
调用后的内容,至少是后续的
标记。
TypeError: $ is not a function (line 5 in header.js)
var scrollHandler = function() {
    var scrollTop = $(window).scrollTop(); // line 5 that throws the error
    // more code
};

$(document).ready(function() {
    if ($(document).width() >= 768) {
        var header = false;
        //register function which is called on scroll
        $(window).scroll(scrollHandler);
    }
});