找不到元素的孩子

Mar*_*all 0 javascript jquery

由于某种原因,我无法从div的类名中获取孩子.slideshow-dots.这是与它的孩子的div:

<div class="slideshow-dots">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
Run Code Online (Sandbox Code Playgroud)

这是错误:

未捕获的TypeError:无法读取未定义的属性"className"

下面是我的代码,我也无法调用公共方法showSlides.

(function($) {
    $.fn.MarvSimpleGallery = function( options ) {
      var instance = this;
      instance.index = 1;

      var settings = $.extend({
        // These are the defaults.
        arrows: true,
        dots: true,
        numbers: true
      }, options );

      var init = function() {
        instance.dotCont = instance.find('.slideshow-dots')[0];
        instance.slides = instance.find('.mySlides');

        // Assign event listeners
        instance.find('.prev').click(function() { instance.showSlides(instance.index += -1); });
        instance.find('.next').click(function() { instance.showSlides(instance.index += 1); });

        // Initiate dot controls
        $.each(instance.slides, function(index, data) {
          var dot = $('<span></span>');
          dot.addClass('dot');
          dot.click(function() { instance.showSlides(instance.index = (index + 1)); });

          $(instance.dotCont).append(dot); 
        });

        // Show initial slide


      }();

      instance.showSlides = function(n) {
        console.log('Slide: ' + n);
        if (n > (instance.slides).length) instance.index = 1;
        if (n < 1) instance.index = (instance.slides).length;

        var slideCount = (instance.slides).length;

        $.each(instance.slides, function(index, data) {
          data.style.display = "none";
          $(data).prepend($('<div></div>').addClass('numbertext').append((index + 1) + ' / ' + slideCount));
        });

        instance.slides[instance.index-1].style.display = "block"; 
        $(instance.dotCont).find('dots')[instance.index-1].className += " active";
      };

    }
  }(jQuery));
Run Code Online (Sandbox Code Playgroud)

jac*_*app 5

尝试

$(instance.dotCont).find('dot')[instance.index-1].className += " active";
Run Code Online (Sandbox Code Playgroud)

代替

$(instance.dotCont).find('dots')[instance.index-1].className += " active";
Run Code Online (Sandbox Code Playgroud)

您的子元素具有类"点"而不是"点".

编辑 - 如评论中所述:

我忘了点:最后的句子必须是

$(instance.dotCont).find('.dot')[instance.index-1].className += " active";
Run Code Online (Sandbox Code Playgroud)

  • 请添加一些有关此代码有助于OP的原因/方式的说明.这将有助于提供未来观众可以学习的答案.有关详细信息,请参阅[此Meta问题及其答案](http://meta.stackoverflow.com/q/256359/215552). (2认同)