2015-11-13 74 views
-1

功能我有一个代码代码与参数

jQuery(function() { 
    jQuery(".class1").each(function() { 
    jQuery(".class2").hide("fast"); 
    jQuery(this).children("input").click(
     function() { 
     if (jQuery(this).parent().hasClass('class3')) { 
      jQuery(".class2").toggle("slow"); 
     } else { 
      jQuery(".class2").hide("slow"); 
     } 
     }); 
    }); 
}); 

我怎样才能改变它与参数的Class1,Class2中,CLASS3许多使用可重复使用的功能?

+1

你需要学习如何做一个功能?我不明白 –

+0

只是做一个函数并传递三个_class_作为参数。 – TGrif

+0

我试过做一些使用这样的代码就像一个函数:inputshow('class1','class2','class3'),其中'class1'等将是一个真实的类,例如,上面的代码使用在许多案例。 –

回答

1

在这里你做出这样的类名称参数,这样你就可以创建一个功能:

var exampleFunction = function(class1, class2, class3) { 
    jQuery(class1).each(function() { 
    jQuery(class2).hide("fast"); 
    jQuery(this).children("input").click(
     function() { 
     if (jQuery(this).parent().hasClass(class3)) { 
      jQuery(class2).toggle("slow"); 
     } else { 
      jQuery(class2).hide("slow"); 
     } 
     }); 
    }); 
} 

,然后调用它像这样:

exampleFunction('.class1','.class2','class3'); 
0

我就简单包装您的相关代码的功能如下面的doSomething功能,然后从你想要调用你的功能的任何地方,你可以做到以下几点:

jQuery(function(){ 
    var class1 = jQuery(".class1"), 
     class2 = jQuery(".class2"), 
     class3 = "class3"; 

    // Reusable function doSomething 
    doSomething(class1, class2, class3name); 
}); 

function doSomething(class1, class2, class3name){ 
    class1.each(function() { 
    class2.hide("fast"); 
    jQuery(this).children("input").click(
     function() { 
     if (jQuery(this).parent().hasClass(class3)) { 
      class2.toggle(slow); 
     } else { 
      class2.hide("slow"); 
     } 
     }); 
    }); 
} 

我曾经为了给类更多的意义var,但是如果你想要的东西,你越短可以调用函数像这样:

doSomething(jQuery(".class1"), jQuery(".class2"), "class3"); 
0
jQuery(function(){ 
    jQuery(".' + class1 + '").each(
    function() { 
    jQuery(".' + Class1 + '").hide("fast"); 
     jQuery(this).children("input").click(
      function(){ 
       if (jQuery(this).parent().hasClass('class3')) { 
        jQuery(".' + Class2 +'").toggle("slow"); 
       } else { 
        jQuery(".' + Class2 +'").hide("slow"); 
       } 
      }); 
    }); 
});