2013-08-16 34 views
0

這裏是一個非常非常非常簡化的例子。javascript傳遞函數名稱作爲參數不工作與jQuery顯示隱藏

我想通過一個函數名稱「顯示」或「隱藏」作爲參數。

但它不會工作,請你幫忙?

if(a==true){ 
showOrhide (hide); 
}else{ 
showOrhide (show); 
} 

var showOrhide = function(doThis){ 
    $("#myDiv").doThis(); 
}; 
+0

的可能重複的[JavaScript對象:由名稱作爲字符串訪問變量性質](http://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-字符串) –

回答

3

它的工作是這樣的:

var showOrhide = function(doThis) { 
    $("#myDiv")[doThis](); 
}; 

if(a) { 
    showOrhide('hide'); 
} else { 
    showOrhide('show'); 
} 

Hoever,它仍然非常難看。 jQuery有一個toggle()方法接受一個布爾參數,它會更合適:

$("#myDiv").toggle(!a); 
+0

+1爲切換解決方案。比我的好多了。 –

+0

感謝您的解決方案 - 它沒有與切換,但與概念。非常感謝您的幫助 –

0

如果只想通過showhide功能,你可以只傳遞他們的名字,並呼籲他們以這種方式:

if(a==true){ 
    showOrhide ('hide'); 
}else{ 
    showOrhide ('show'); 
} 

function showOrhide (doThis){ 
    $("#myDiv")[doThis](); 
}; 
+0

這會失敗。 – Neal

+0

@尼爾你爲什麼這麼認爲? –

+1

因爲'showOrhide'在if語句中是'undefined'。 – Neal

-2

或使用eval的另一種方法。

var showOrhide = function(doThis){ 
    eval("$('#myDiv')." + doThis + "()"); 
};  

if(false==true){ 
    showOrhide ('hide'); 
}else{ 
    showOrhide ('show'); 
} 
+0

eval is evil:P –

+0

哇...不會...這會失敗... – Neal

+2

而最不必要的評價獎用於...... – JJJ