$ 不是 Chrome 扩展程序中的有效函数?

问题描述 投票:0回答:2

所以我打算将我的 Tampermonkey 用户脚本(这是一个让您访问列表中随机链接的按钮)发布到 Chrome Web Store,今天我一直在测试它,但出现了错误:

Uncaught TypeError: $ is not a function
    at Chain Finder.user.js:258
    at Chain Finder.user.js:261

如果你想看看我的脚本:

(function() {
    const $ = window.$;

    var randomLink = function () {
        // Beggining of target list
        var links = [
            "torn.com/profiles.php?XID=2410074",
            "torn.com/profiles.php?XID=2393322",
            "torn.com/profiles.php?XID=2049797",
            "torn.com/profiles.php?XID=2268673",
            "torn.com/profiles.php?XID=2059647"
            // More links.... but I cut them so it's easier to understand.
        ];

        // End of target list
        // by counting the number of links in the array
        var max = (links.length)

        // now generate a random number
        var randomNumber = Math.floor(Math.random()*max);

        // use that random number to retrieve a link from the array
        var link = links[randomNumber];

        // change the location of the window object
        return "https://" + link;
    }

    // Opens a new tab.
    function openInNewTab(url) {
        var win = window.open(url, '_blank');
        win.focus();
    }

    function main() {
        $('.buttons-list').append(`<a id="mc-btn" href="#" class="profile-button" style="width:99px;text-align:center">
                  <img src='https://i.imgur.com/TQdk3Pp.png'>
                                  </a>`);
        $('#mc-btn').on('click', () => openInNewTab(randomLink()));
    }

    //Here's the error:

    $(document).ready(() => {
        main();
    });
})();

如果你能告诉我那里出了什么问题,我将非常感激。

编辑:我已经学会了 JavaScript。现在一切看起来都是那么容易!不管怎样,谢谢你的帮助。

javascript tampermonkey userscripts
2个回答
0
投票

确保在脚本中的某个位置包含这两行代码,放置 var $ = window.jQuery;位于代码开始处的上方,然后将 // @require http://code.jquery.com/jquery-3.4.1.min.js 放在 // 其余行的顶部。

示例:

// ==UserScript==
// @name         Example
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description
// @author       Username
// @require      http://code.jquery.com/jquery-3.4.1.min.js
// @grant GM_addStyle
// @grant GM.listValues
// @grant GM_setValue
// @grant GM_getValue
// @match *
// @match https://*/*
// @match http://*/*
// @match *://*/*
// ==/UserScript==

(function() {
    'use strict';

    // Your code here...
})();
var $ = window.jQuery;

0
投票

如果脚本中未包含 Jquery,通常会显示该错误。

© www.soinside.com 2019 - 2024. All rights reserved.