2011-12-13 62 views
0

這裏一定有一些小的漏洞。我只是試圖選擇DL中的所有DT元素並插入一些HTML並添加一個單擊事件,但它似乎只適用於第一個DT。jQuery查找/每個腳本不能正常工作

下面是從我的插件代碼片段:

return this.each(function(){ 
      var questions = $(this).find('dt'); 
      questions.each(function(){ 

       $(this).attr("title","Show answer"); // add screen tip 
       $(this).wrapInner("<span class='faqToggleQues' />"); 
       $(this).prepend("<span class='faqToggleNumber'>"+numPrefix+(i+1)+numSubfix+"</span>"); 

      }); 
     }); 

而且我主持上的jsfiddle http://jsfiddle.net/mindfriction/u6WYQ/

回答

0

根據您所提供的我已經更新了代碼http://jsfiddle.net/u6WYQ/6/ 需要新的鏈接代碼要使用defaults.numPrefix而不是numPrefix.Also,您可以通過使用init方法隱藏dd默認值。也可以將選項與默認值合併以應用用戶設置。

+0

對不起KVC,我添加了錯誤的jsfiddle鏈接..它應該是TTP://jsfiddle.net/mindfriction/u6WYQ/ – htmlr

+0

我發現這個問題是一個underclared變量拋出jQuery所以它沒有進行到每個函數的下一個循環.. – htmlr

+0

是的,我已經通過默認變量的數量前綴,你可以切在已發佈的鏈接中修改已修改的代碼 – kvc

0
 
$(document).ready(function() { 
$('dt').each(function(){ 

       $(this).attr("title","Show answer"); // add screen tip 
       $(this).wrapInner(""); 
       $(this).prepend(""+numPrefix+(i+1)+numSubfix+""); 

      }); 

}); 
+0

嗨的Sudhir,這是一個插件中,雖然因此爲什麼它在 「返回this.each(函數(){}」砌塊。該插件被稱爲像這樣$( '#DL常見問題解答')faqToggle() – htmlr

0

看到我更新的代碼http://jsfiddle.net/u6WYQ/11/

  1. $.extend

  2. 對其進行處理以增加數量問題之前宣佈的默認選項$.fn.faqToggle.defaults,請參閱內。每個(具有idx),而不是外部。每個(參考i

  3. 調用自定義jquery方法faqToggle(function($){ ... }(jQuery))身體,而不是外界

完整的代碼

   (function($){ 
    $.fn.faqToggle = function(options){ 
     // declare the default options before processing them 
     $.fn.faqToggle.defaults = { 
      numPrefix: 'Q', 
      numSubfix: '.', 
      showTooltip:'Show answer', 
      hideTooltip:'Hide Answer' 
     } 

     var opts = $.extend({},$.fn.faqToggle.defaults, options); 


     function onClick(){ 
      if ($(this).next('dd').is(":hidden")) { // if the answer is hidden show it 
       $(this).next('dd').show(); 
       $(this).attr("title","Hide answer"); // update screentip 
      } else { 
       $(this).attr("title","Show answer"); // update screentip 
       $(this).next('dd').hide(); // if the answer is shown hide it 
      } 
     } 


     return this.each(function(i){ 

      var questions = $(this).find('dt'); 
      var answers = $(this).find('dd'); 
      answers.hide(); // hide answers initially 

      // for incrementing question number, referto inner .each, not the outer 
      questions.each(function(idx){ 
       $(this).attr("title","Show answer"); // add screen tip 
       $(this).wrapInner("<span class='faqToggleQues' />"); 
       $(this).prepend("<span class='faqToggleNumber'>"+opts.numPrefix + (idx+1) + opts.numSubfix+"</span>"); 

       $(this).click(onClick); 

      }); 



     }); 


    }; 

// apply the custom jquery method in the (function($){ ... }(jQuery)) 
    $('#faqList').faqToggle(); 
})(jQuery);