2014-01-29 64 views
0

我有一個簡單的函數,當用戶點擊給定的複選框時顯示一個div。我想在另一個複選框上具有相同的行爲,所以我想將它概括爲傳遞要顯示的元素的函數。定義泛型函數jquery

但我不知道JQuery的語法來這樣做。它在頁面加載時自動觸發。有人有想法嗎?

代碼:

$(document).ready(function() { 

$("#transcricao").change( 
    function(){ 
     if ($('.form_transcr').css('display') === 'none') { 
      $('.form_transcr').fadeIn(); 
     } else { 
      $('.form_transcr').fadeOut(); 
     } 
    } 
); //This is working fine! 


$("#traducao").change(show_hide($('.form_trad'))); 
//This is auto-trigerring without user action... 

}); 

這裏是我的功能:

function show_hide($elm){ 

//This is the "generalized" function that I'd like to use on both 
//checkboxes, just passing the element. 

if ($($elm).css('display') === 'none') { 
     $($elm).fadeIn(); 
    } else { 
     $($elm).fadeOut(); 
    } 
} 
+0

這不就是'fadeToggle()'呢? – Barmar

回答

0

其自動觸發,無需用戶操作,因爲你正在調用它。

使用

$("#traducao").change(function() { 
    show_hide($('.form_trad')); 
}); 

當你逝去的jQuery對象所以用它直接

function show_hide($elm) { 
    //This is the "generalized" function that I'd like to use on both 
    //checkboxes, just passing the element. 
    if ($elm.css('display') === 'none') { 
     $elm.fadeIn(); 
    } else { 
     $elm.fadeOut(); 
    } 
} 
0

.change()的參數應該是一個函數。你沒有通過一個函數,你的調用了的函數。

$("#traducao").change(function() { 
    show_hide($('.form_trad')); 
}); 

順便說一句,你show_hide功能似乎等同於jQuery的fadeToggle方法,因此它可以是:

$("#traducao").change(function() { 
    $(".form_trad").fadeToggle(); 
});