jQuery find/each脚本不工作

jQuery find/each script not working

本文关键字:工作 脚本 each find jQuery      更新时间:2023-09-26

我一定忽略了一些小事。我只是试图选择DL中的所有DT元素并插入一些HTML并添加单击事件,但它似乎只适用于第一个DT。

下面是我的插件的代码片段:

 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/

根据您提供的新链接,我已经更新了代码http://jsfiddle.net/u6WYQ/6/需要使用默认值。numPrefix而不是numPrefix。也可以通过init方法隐藏dd默认值。

$(文档)时函数(){$ (dt) . each(函数(){(美元)。attr("标题"、"显示答案");//添加屏幕提示(美元).wrapInner (" ");(美元).prepend (" + numPrefix + (i + 1) + numSubfix + " ");});});

查看我更新的代码http://jsfiddle.net/u6WYQ/11/

  1. $.extend中处理之前声明默认选项$.fn.faqToggle.defaults

  2. 递增题数为内each (idx所指),而非外each (i所指)

  3. (function($){ ... }(jQuery))正文中调用自定义jquery方法faqToggle,而不是在

完整代码

                (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);