2017-05-04 58 views
0

由於某種原因,我無法從類名爲.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> 

這是錯誤:

Uncaught TypeError: Cannot read property 'className' of undefined

下面是我的代碼,我也無法調用公共方法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)); 
+0

在某些時候,'instance.index-1'不是一個有效的關鍵用於代碼最後一行的集合。分享一個工作示例(jsfiddle,stacksnippets,codepen ....) –

+0

您能否幫助我們,並給我們一個提示,以確定哪一行拋出錯誤? –

+1

另一個問題:爲什麼您將vanilla JS與jQuery混合? –

回答

5

嘗試

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

,而不是

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

您的孩子元素具有一流的 '點',而不是 '點'。

編輯 - 在評論說:

我忘了點: 最後一句必須是

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

請添加一些解釋爲什麼/這個代碼如何幫助OP。這將有助於提供未來觀衆可以從中學習的答案。請參閱[這個元問題及其答案](http://meta.stackoverflow.com/q/256359/215552)瞭解更多信息。 –

+0

該代碼將搜索''子元素,而不是'class = dot'子元素。 –