javascript element.querySelector(".exampleClass") 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32675337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:36:20  来源:igfitidea点击:

element.querySelector(".exampleClass") is not a function

javascriptcssdomresponsive-designcss-transforms

提问by user3562480

I am trying to build a responsive carousel and am getting an error in the following code. I've tried using JQuery, other selection methods but they all return the same error.

我正在尝试构建响应式轮播,但在以下代码中出现错误。我试过使用 JQuery 和其他选择方法,但它们都返回相同的错误。

I try to select the element here, first my accessing its parent element

我尝试在这里选择元素,首先我访问它的父元素

     var carousel = $('#carousel');
     var container = carousel.querySelector('.carousel-container');

The about code returns and ERROR that carousel.querySelector is not a function.

关于代码返回和错误,carousel.querySelector 不是一个函数。

Which creates a problem, and also screws up the resizing function below:

这产生了一个问题,并且还搞砸了下面的调整大小功能:

  function slideTo(index){
      index = index < 0 ? totalItems -1 : index >= totalItems ? 0 : index;
      container.style = container.style.transform = 'translate(-' + (index * percent) + '%, 0)';
       currentIndex = index;
   }

Container.style in the third line of the function returns an ERROR that I cannot set a property on container.style as it is "undefined"

函数第三行中的 Container.style 返回一个错误,我无法在 container.style 上设置属性,因为它是“未定义的”

I REALLY just need to be able to add the CSS "transform : translate" property to the container element.

我真的只需要能够将 CSS“transform : translate”属性添加到容器元素。

I am at a loss for things to try... would really appreciate some feedback!

我对尝试的事情感到茫然......真的很感激一些反馈!

回答by chiliNUT

querySelectoris a native JS method, and carouselis a jQueryobject. If you are using jQuery, there is 0 reason to be using queryselector.

querySelector是一个原生的JS方法,并且carousel是一个jQuery对象。如果您正在使用jQuery,则有 0 个理由使用queryselector.

jQuery

jQuery

var carousel = $('#carousel'); //jQuery object
var container = carousel.find('.carousel-container'); //jquery object of carousel-container

DOM

DOM

var domCarousel=carousel.find('.carousel-container')[0];

which is roughly equivalent to

这大致相当于

domCarousel=document.getElementById('carousel').querySelector('.carousel-container');