首页 > 解决方案 > 为什么我的 jQuery 就绪函数调用不起作用?

问题描述

我试图jQuery(document).ready在我的 main.js 文件中调用 from jQuery。但我在 Chrome 控制台中收到以下错误: main.js:3 Uncaught SyntaxError: Invalid or unexpected token.

索引.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Document</title>
    <script type="text/javascript" src="node_modules/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript" src="main.js"></script>
</head>

<body>

    <h1>Dropdown Test</h1>

    <div class="menu-bar">

    </div>

    <div class="dropdown-box">
        <div class="dropdown-label" onmouseover="
        (function(){main.onLabelHover();})()
        ">
            Erbjudanden
        </div>
        <div class="dropdown">
            <div class="dropdown-option">
                Option 1
            </div>
            <div class="dropdown-option">
                Option 2
            </div>
            <div class="dropdown-option">
                Option 3
            </div>
            <div class="dropdown-option">
                Option 4
            </div>
            <div class="dropdown-option">
                Option 5
            </div>
        </div>
    </div>


</body>

</html>

主.js:

jQuery(document).ready(function() {
    console.log("jQuery is working!");
});​

// var main = {

//     run() {
//         document.body.addEventListener('click', this.onAnyClick, true);
//     },

//     onAnyClick() {
//         alert("click");
//     },

//     onLabelHover: function() {
//         this.openDropdown();
//     },

//     openDropdown() {
//         var options = this.getDropdownOptions();
//         console.log(options);
//         for (let option of options) {
//             option.classList.add("dropdown-option-opened")
//         }
//     },

//     getDropdownOptions() {
//         var options = document.getElementsByClassName("dropdown-option");
//         return options;
//     }

// };

从 node_modules 导入有效,因为我在控制台中没有收到关于在文件系统中查找 jQuery 的投诉。我什至尝试从 Google api url 获取 jQuery,但调用jQuery(document).ready函数时仍然出现相同的错误。

我也尝试了$语法而不是打字jQuery,但同样的错误仍然存​​在。

谢谢!

标签: javascripthtmljquery

解决方案


我刚刚对其进行了测试,它工作正常,但由于某种原因,你的逗号旁边有一个隐藏的字符。

你有这个:

jQuery(document).ready(function() {
    console.log("jQuery is working!");
});​ // here delete this command and add it again and save it

删除逗号并再次添加将修复它。不要忘记保存它。


推荐阅读