【问题标题】:JQuery: '$' is not defined [duplicate]JQuery:'$'未定义[重复]
【发布时间】:2018-09-21 01:16:57
【问题描述】:

我有一个具有此文件层次结构的 React 项目:

在 index.html 中我正在导入 JQuery:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Sentify</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

在 model.js 中,我正在尝试使用它:

$(function(){
  var template = $('#template').html();
  var baseUrl = 'http://node-cors-server.herokuapp.com';

  if(/^http\:\/\/localhost/.test(window.location.href)){
    baseUrl = 'http://localhost:3000'; // for running/testing locally
  }

  $('article').each(function(index, example){
    // get example metadata, render template
    var $example = $(example),
        method = $example.data('method'),
        url = baseUrl + $example.data('url');
    $example.html(template);

    // fetch subnodes from newly templatized content, fill out
    var $h1 = $example.find('h2'),
        $pre = $example.find('pre'),
        $button = $example.find('button'),
        $result = $example.find('textarea'),
        $error = $example.find('p.error');
    $h1.text('Example #' + (index + 1) + ':');
    $pre.text(method + ' ' + url);

    // bind click event to actually fetch stuff from remote server
    $button.click(function(){
      $result.text('');
      $error.text('');
      $button.attr('disabled', 'disabled');
      $.ajax({
        url: url,
        method: method,
        success: function(data, state, res){
          $button.removeAttr('disabled');
          $result.css('border-color', 'black');
          if(data){
            $result.text(data.text);
          }else{
            $result.text('STATUS CODE: ' + res.status);
          }
        },
        error: function(data, state){
          $button.removeAttr('disabled');
          $result.css('border-color', 'red');
          $error.text(state);
          console.log(data);
        }
      });
    });
  });
});

const httpOptions = {
  headers: {'X-Mashape-Key': 'YOUR_API_KEY'}
};

const Model = function () {
  let container = 'Map';
  let observers = [];
  let searchInput = '';
  let sentimentData = {"data": [
                                {"text": "I love Titanic.", "id":1234, "polarity": 4},
                                {"text": "I love Titanic.", "id":1234, "polarity": 4},
                                {"text": "I don't mind Titanic.", "id":1234, "polarity": 2},
                                {"text": "I dislike Titanic.", "id":1234, "polarity": 4},
                                {"text": "I hate Titanic.", "id":4567, "polarity": 0},
                                ]
                      };



  // API Calls

  this.setContainer = function(input){
    let container = input;
    notifyObservers();
  }

  this.getContainer = function(){
    return container;
  }

  this.setSentimentData = function(result){
    let sentimentData = result;
  }

  this.getSentimentData = function(){
    return sentimentData;
  }

  this.getTweets = function(query){
    let url = "/1.1/search/tweets.json?q=";
    const queryParam = encodeURIComponent(query);
    url += queryParam;

  }

  // API Calls
  this.sentimentAnalysis = function (tweets) {

    // const url = 'http://www.sentiment140.com/api/bulkClassifyJson' + searchInput //TO DO: Fix correct URL
    // return fetch(url, httpOptions)
    //   .then(processResponse)
    //   .catch(handleError)
  }




  // Observer pattern

  this.addObserver = function (observer) {
    observers.push(observer);
  };

  this.removeObserver = function (observer) {
    observers = observers.filter(o => o !== observer);
  };

  const notifyObservers = function () {
    observers.forEach(o => o.update());
  };
};

export const modelInstance = new Model();

model.js 导致多个错误,似乎都与 model.js 运行时未加载 JQuery 有关:

index.js:2178 ./src/model/model.js
  Line 1:   '$' is not defined  no-undef
  Line 2:   '$' is not defined  no-undef
  Line 9:   '$' is not defined  no-undef
  Line 11:  '$' is not defined  no-undef
  Line 30:  '$' is not defined  no-undef

对此我能做些什么?在 model.js 中导致错误的代码取自 here。我们正在尝试使用它在我们的应用程序中使用 Twitter API,而不会出现 CSRF 错误。

【问题讨论】:

  • model.js 如何以及在何处包含在页面中?
  • 也许您的model.js 是在页面中包含 jquery 之前包含的?
  • 我们不知道如何检查,因为我们不确定 React 项目从哪里开始执行。我们怎样才能学会呢?
  • 我建议,通过 npm 安装 jQuery,而不是 CDN,然后是 import $ from "jquery";

标签: javascript jquery node.js


【解决方案1】:

这是您在代码中不使用 jQuery 插件时出现的常见错误之一。

也许您可能想看看this question。这可能会帮助您解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-27
    • 2015-07-13
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 2017-05-01
    相关资源
    最近更新 更多