JavaScript/jQuery - “$ 未定义 - $function()”错误

IT技术 javascript jquery
2021-02-23 04:00:35

我正在尝试运行 JavaScript/jQuery 函数,Firebug收到错误消息:

$ is not defined $(function()".

JavaScript 代码放置在一个core.js调用和引用的文件中index.php是什么导致了这个错误?

JavaScript:

<script type="text/javascript">
    var formObject = {
        run : function(obj) {
            if (obj.val() === '') {
                obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
            } else {
                var id = obj.attr('id');
                var v = obj.val();
                jQuery.getJSON('/mod/update.php', { id : id, value : v }, function(data) {
                    if (!data.error) {
                        obj.next('.update').html(data.list).removeAttr('disabled');
                    } else {
                        obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
                    }
                });
            }
        }
    };

    $(function() {

        $('.update').live('change', function() {
            formObject.run($(this));
        });

    });
</script>

PHP/HTML

<html>
    <select name="main" id="category" class="update">
    <option value="">Select one</option>

        <? if (!empty($list)) { ?>
            <? foreach($list as $row) { ?>
                <option value="<?php echo $row['id']; ?>">
                    <? echo $row['name']; ?>
                </option>

            <? } ?>
        <? } ?>

    </select>
</html>
6个回答

您一定没有让 jQuery 可用于您的脚本。

将此添加到文件的顶部:

<script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>

此问题与未正确添加到 PHP/JSP/ASP 文件的 jQuery/JavaScript 文件有关。这会从源代码中获取 jQuery 代码。您可以下载它并在服务器上本地引用它,这会更快。

或者可以直接将其链接到 jQuery 或 GoogleCDN 或 MicrosoftCDN。

如何将 jQuery 添加到您的网页

我已将 jQuery CDN 添加到我的 HTML 中,但仍然出现此错误。有任何想法吗?
2021-04-21 04:00:35
最好使用 https 而不是 http,否则当网站通过 https 运行时它不会加载。
2021-04-24 04:00:35
@Blairg23 清除浏览器中的所有缓存并检查它。
2021-05-13 04:00:35
对!检查错误控制台是否有任何GET消息;对我来说,这是一个简单的、愚蠢的换行,加<script>..jquery..</script>在行的中间
2021-05-21 04:00:35

尝试:

(function($) {
    $(function() {
        $('.update').live('change', function() {
            formObject.run($(this));
        });
    });
})(jQuery);

通过使用这种方式,您可以确保全局变量 jQuery 将绑定到闭包内的“$”。只需通过插入以下内容来确保 jQuery 正确加载到页面中:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

将“ http://code.jquery.com/jquery-1.7.1.min.js替换为您的 jQuery 源在页面上下文中所在的路径。

这可能对某人有用:

如果您已经使用 jQuery 但仍然出现此错误,请检查您是否在使用它的 js 之前包含 jQuery,特别是如果您在 ASP.NET C# 中使用 @RenderBody()

如果在@RenderBody() 调用的视图中包含js,则必须在@RenderBody() 之前包含jQuery。

您需要在页面上包含 jQuery 库。

您可以在此处下载 jQuery自行托管,也可以从 Google 或 Microsoft 等外部资源链接。

谷歌的:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

微软的:

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js">

包含 jquery.js,如果包含,则在任何其他 JavaScript 代码之前加载它。