Добавление к main. js причин - Uncaught TypeError: this.elements не является функцией - PullRequest
1 голос
/ 13 апреля 2020

Я прохожу курс Udemy и попал в модуль по написанию нашей собственной версии jQuery. Во время этого модуля я создал файл js, squery. js. Целью этого файла является устранение необходимости использовать символ точки для идентификации классов в основном файле. js. Я записал оба файла дословно в то, что использовал инструктор, но по какой-то причине у меня выскакивает несколько ошибок.

В сквери. js Я получаю следующую ошибку:

ERROR: Parsing error: The keyword 'class' is reserved

В моем основном файле. js я получаю эту ошибку:

ERROR: 'sQuery' is not defined.[no-undef]

В консоли Chrome я получаю следующие ошибки:

jQuery.Deferred exception: this.elements is not a function TypeError: this.elements is not a function
    at squery.addClass (file:///C:/Users/jason/Desktop/Projects/Web-Course/js/squery.js:9:12)
    at HTMLDocument.<anonymous> (file:///C:/Users/jason/Desktop/Projects/Web-Course/js/main.js:31:25)
    at e (https://code.jquery.com/jquery-3.5.0.min.js:2:30005)
    at t (https://code.jquery.com/jquery-3.5.0.min.js:2:30307) undefined
S.Deferred.exceptionHook @ jquery-3.5.0.min.js:2
t @ jquery-3.5.0.min.js:2
setTimeout (async)
(anonymous) @ jquery-3.5.0.min.js:2
c @ jquery-3.5.0.min.js:2
fireWith @ jquery-3.5.0.min.js:2
fire @ jquery-3.5.0.min.js:2
c @ jquery-3.5.0.min.js:2
fireWith @ jquery-3.5.0.min.js:2
ready @ jquery-3.5.0.min.js:2
B @ jquery-3.5.0.min.js:2
Uncaught TypeError: this.elements is not a function
    at squery.addClass (squery.js:9)
    at HTMLDocument.<anonymous> (main.js:31)
    at e (jquery-3.5.0.min.js:2)
    at t (jquery-3.5.0.min.js:2)
addClass @ squery.js:9
(anonymous) @ main.js:31
e @ jquery-3.5.0.min.js:2
t @ jquery-3.5.0.min.js:2
setTimeout (async)
S.readyException @ jquery-3.5.0.min.js:2
(anonymous) @ jquery-3.5.0.min.js:2
e @ jquery-3.5.0.min.js:2
t @ jquery-3.5.0.min.js:2
setTimeout (async)
(anonymous) @ jquery-3.5.0.min.js:2
c @ jquery-3.5.0.min.js:2
fireWith @ jquery-3.5.0.min.js:2
fire @ jquery-3.5.0.min.js:2
c @ jquery-3.5.0.min.js:2
fireWith @ jquery-3.5.0.min.js:2
t @ jquery-3.5.0.min.js:2
setTimeout (async)
(anonymous) @ jquery-3.5.0.min.js:2
c @ jquery-3.5.0.min.js:2
fireWith @ jquery-3.5.0.min.js:2
fire @ jquery-3.5.0.min.js:2
c @ jquery-3.5.0.min.js:2
fireWith @ jquery-3.5.0.min.js:2
ready @ jquery-3.5.0.min.js:2
B @ jquery-3.5.0.min.js:2

Я не получаю никаких ошибок консоли, пока не добавлю следующий код в main. js:

sQuery("my-selector").addClass("MYNEWCLASS");

Мой код:

squery. js

class squery {
  constructor(el) {
    this.elements = document.getElementsByClassName(el);
  }

  addClass(cl) {
    var count = 0;
    while(count < this.elements.length){
      this.elements(count).className += " " + cl;
      count++;
    }
  }
}

function sQuery(el) {
  var element = new squery(el);
  return element;
}

основной. js

$(document).ready(function () {

  sQuery("my-selector").addClass("MYNEWCLASS");
  // Remove Right Click Menu and Create our own context menu
  $(document).on('contextmenu', function () {
    return false;
  })
  $(document).on('mousedown', function (event) {
    event.preventDefault();

    if(event.which == 3){

      $('.hidden').removeClass('shown');

      if ($(event.target).is('img')) {
        $('.saveimg, .newtab').addClass('shown');
      }else if ($(event.target).is('a')) {
        $('.newtab').addClass('shown');
      }

      console.log(event.pageY, event.pageX);

      $('#context').css({
        top: event.pageY,
        left: event.pageX
      });
      $('#context').fadeIn();
    }else if (event.which == 1) {
      $('#context').fadeOut();
    }

  })

  // Dropdown Menu
  $('[data-trigger="dropdown"]').on('mouseenter', function () {
    var submenu = $(this).parent().find('.submenu');
    submenu.fadeIn(300);

    $('.profile-menu').on('mouseleave', function () {
      submenu.fadeOut(300);
    })

  });

  // Appending Prepending and Replacing
  $('#prepend, #append, #replace').on('click', function (e) {
    e.preventDefault();
    var el = $(e.currentTarget);
    var action = el.attr('id');
    var content = $('.text').val();

    if(action == "prepend"){
      console.log("Prepending...");
      $('#main').prepend('<a href="#">' + content + '</a>');
    }else if (action == "append") {
      console.log("Appending...");
      $('#main').append(content);
    }else if (action == "replace") {
      console.log("Replacing...");
      $('#main').html(content);
    }

    $('.text').val('');
  });

});

1 Ответ

0 голосов
/ 14 апреля 2020

В вашем коде есть синтаксическая ошибка:

this.elements(count) будет this.elements[count]

this.element(count) будет означать, что это функция, и вы получаете ошибку, потому что она это массив.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...