【问题标题】:$ is not defined Javascript [duplicate]$未定义Javascript [重复]
【发布时间】:2017-10-11 00:12:10
【问题描述】:

我正在编写一段当前在 tampermonkey 中的代码,但我无法弄清楚为什么我在 google chrome 的控制台中出现此错误,“执行脚本 'PalaceBOT' 失败!$ 未定义”,我有另一个使用相同主体的脚本,我没有遇到这些问题。

脚本:

// ==UserScript==
// @name         SupremeBOT
// @namespace
// @version      0.1
// @description
// @author       @alfiefogg_
// @match        http://www.supremenewyork.com/shop/*
// @exclude      http://wwww.supremenewyork.com/shop/cart
// @require      https://gist.github.com/raw/2625891/waitForKeyElements.js
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
// @grant        none
// ==/UserScript==
var mySize = "large"; //Change to appropriate size
var productSort = "accessories"; //Change to appropriate size
(function() {
    var articles = $(".product-grid-item clearfix");
    if(productSort != "all"){
        for(var i = 0; i < articles.length;i++)
        {
            var category = $(articles[i]).find("a").attr("href");
            if(category.indexOf(productSort) == -1){
                articles[i].remove();
                document.getElementsByClassName("product-grid-item clearfix")[4].click();
            }
        }
    }
    waitForKeyElements("#img-main", exe);
})();
function exe(){
    selectSize();
    goCheckout();
}
function goCheckout(){
    var x = document.getElementById("add-remove-buttons");
    var z = x.getElementsByClassName("button")[0];

    if(z.className != "button remove"){
        z.click();
        setTimeout(goCheckout ,100);
    }else{
        window.location = "https://www.supremenewyork.com/checkout";
    }
}
function selectSize(){
    var sizeObj = document.getElementById("size");
    for(var i=0,sL=sizeObj.length;i<sL;i++){
        if(sizeObj.options[i].text == mySize){
            sizeObj.selectedIndex = i;
            break;
        }
    }
}

请记住,这不是一个完成的脚本。

【问题讨论】:

  • 请添加您的html
  • @A.Fogg : 你在代码的什么地方加载了 jQuery?
  • 查看 Liams 评论,这是一个重复的问题,其他答案可能是您的问题,并且不知何故 jQuery 库未加载到您的脚本中。

标签: javascript jquery tampermonkey


【解决方案1】:

从窗口对象中获取 jQuery

var $ = window.jQuery;

【讨论】:

  • 将此行添加到脚本的顶部范围对我有用。我们只需要将 jquery 对象从 window 中取出,tampermonkey 将它从 // @require 中取出(并将其别名为 $)。像魅力一样工作,谢谢!
  • 我想要某种方式来将其标记为已识别,就像在 JSLint 中一样,无需添加额外的代码语句,只需添加注释即可。它已经存在于页面上。
  • 您能进一步解释一下吗?
【解决方案2】:

除了this,我没有找到更好的答案。

一般来说,这段代码定义了库,以便在 Tampermonkey 编辑器中进一步使用。

/*globals MY_LIB*/ 使用它会取消所有警告。

有关更多信息,请查看此 (https://jshint.com/docs/#inline-configuration)。 它解释了什么是全局变量,以及它们是如何工作的。

【讨论】:

    【解决方案3】:

    你需要包含 JQuery $ 不是常规 javascript 的一部分

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 2021-03-02
      • 2015-08-31
      • 2017-04-25
      • 1970-01-01
      • 2014-10-16
      • 2013-06-26
      相关资源
      最近更新 更多