2015-11-13 22 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"); 
       } 
      }); 
    }); 
});