转换jQuery函数,使其易于重用而无需重复

Converting jQuery function to be reused easily without repetition

本文关键字:易于重 函数 jQuery 转换      更新时间:2023-09-26

我有以下函数,将无序列表的每一行淡入和淡出。现在它适用于#skills_hints,但我想把它用于其他#named_hints。是否有一种方法,我可以重用此代码在多个无序列表,而不复制和粘贴整个代码,只是改变id ?

$(document).ready(function(){
    $('#skills_hints .hint');
    setInterval(function(){
        $('#skills_hints .hint').filter(':visible').fadeOut(800,function(){
            if($(this).next('li.hint').size()){
                $(this).next().fadeIn(800);
            }
            else{
                $('#skills_hints .hint').eq(0).fadeIn(800);
            }
        });
    },7000);    
});

下面的代码将完全执行您所发布的内容,并且可以通过不同的id反复调用doit函数(显然您应该重命名它)。

function doit(id){
    $('#'+id+' .hint');
    setInterval(function(){
        $('#'+id+' .hint').filter(':visible').fadeOut(800,function(){
            if($(this).next('li.hint').size()){
                $(this).next().fadeIn(800);
            }
            else{
                $('#'+id+' .hint').eq(0).fadeIn(800);
            }
        });
    },7000);    
}
$(function(){
   doit('skills_hints');
})

一个很好的技巧是把它变成一个闭包,以防你需要一个单独的函数来用作回调,等等

function doit(id_name){
    var id = '#'+id_name + '.hint';
    return (function(){
        $(id);
        setInterval(function(){
            $(id).filter(':visible').fadeOut(800,function(){
                if($(this).next('li.hint').size()){
                    $(this).next().fadeIn(800);
                }
                else{
                    $(id).eq(0).fadeIn(800);
                }
             }
         },7000);
    })
}
//examples
doit_skills = doit('skills_hint');
doit();
doit_foo = doit('foo');
doit_foo()
names = ['a', 'b'];
for(var i=0; i<names.length; i++){
    doit(names[i])();
}

你可以把你的代码转换成jQuery Plugin (http://docs.jquery.com/Plugin)