找不到元素的孩子

时间:2017-05-04 14:40:02

标签: javascript jquery

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

<div class="slideshow-dots">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>

这就是错误:

  

未捕获的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));

1 个答案:

答案 0 :(得分:5)

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

而不是

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

您的孩子元素有班级&#39;点&#39;而不是&#39;点&#39;。

修改 - 如评论中所述:

我忘了点: 最后一句必须是

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