2011-12-13 61 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);