代码转换为带参数的函数

时间:2015-11-13 20:43:42

标签: jquery

我有一个代码

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用于多种用途?

3 个答案:

答案 0 :(得分: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');

答案 1 :(得分: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");

答案 2 :(得分: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");
                }
            });
    });
});