2012-02-02 98 views
0

jQuery函數我嘗試用VAR替換一個jQuery chaned功能,但它不工作(synthax錯誤)替換使用var

Triing是這樣的:

var foo = 'next()'; 
$(this).+foo+.show(); 

是否有可能以某種方式認識到, ? foo是如果條件

+2

只有'eval';別。相反,使用條件。 – 2012-02-02 17:28:45

+2

不,不僅與eval。另外,如果你打算提一下條件語句,你應該向ggzone提供一些關於在哪裏學習它們的建議:) – Kato 2012-02-02 17:32:21

回答

3

其更改爲「下一頁()」中的另一個變種做這樣的:

var foo = 'next'; 
$(this)[foo]().show(); 

通過唯一方法名稱設置爲變量,你可以使用[]符號並使用該變量來檢索jQuery對象的next屬性。

這相當於...

$(this)['next']().show(); 

這相當於...

$(this).next().show(); 
+0

你沒有調用foo的方式 – 2012-02-02 17:30:40

+1

只需要在JavaScript中使用'foo.bar'和'foo ['bar']'意味着同樣的事情,'foo ['bar']'有這樣的優勢,你可以使用變量作爲鍵。 – cdmckay 2012-02-02 17:31:11

+0

你需要'[foo]()'來執行這個方法。 – 2012-02-02 17:31:53

3

試試這個:

var foo = 'next'; 
$(this)[foo]().show(); 
-1

你有兩個選擇,我看到:

var foo = next; // use the OBJECT here, not a string 
$(this).foo().show(); 

OR 

var foo = false; 
if (foo) 
    $(this).next().show() 
else 
    $(this).prev().show();