2011-06-08 89 views
3

我想根據某些條件顯示和隱藏對象(div,文本或btns)。在JQuery中顯示和隱藏對象

在C#中,我們可以寫出像下面的減少值編碼量:

txtA.visible = (type == "A"); 
txtB.visible = (type == "B"); 
txtC.visible = (type == "C"); 

jQuery中,以顯示和隱藏,我用.show()和.hide()方法。 但是,我必須爲這個簡單的功能寫很多行。例如:

if (type == "A") 
    $("#txtA").show(); 
else 
    $("#txtA").hide(); 

if (type == "B") 
    $("#txtB").show(); 
else 
    $("#txtB").hide(); 

if (type == "C") 
    $("#txtC").show(); 
else 
    $("#txtC").hide(); 

有沒有辦法用較少的線路實現相同的功能?謝謝。

回答

10

.toggle(showOrHide)允許一個布爾以顯示或隱藏的元素。

你可以重寫你的榜樣看起來像這樣:

$("#txtA").toggle(type === "A"); 
$("#txtB").toggle(type === "B"); 
$("#txtC").toggle(type === "C"); 

Example on jsfiddle

1

看看JQuery toggle

+0

我認爲這不會減少在這種情況下代碼大小,因爲反覆被有條件地發生。 – 2011-06-08 14:39:25

6

使用三元運算:

(type == "A") ? $("#txtA").show() : $("#txtA").hide(); 
+0

當你有很多元素時,我不明白這會如何減少代碼量,它只是在一行上添加條件。 if(type ==「A」)$(「#txtA」)。show();其他$(「#txtA」)。hide()'幾乎一樣短。 – 2011-06-08 14:51:22

+0

@Gary Green - 我更喜歡你的解決方案 – noinstance 2011-06-08 14:54:12

1

這將顯示當前的類型和隱藏所有的兄弟姐妹元素(我假設他們被放置在一個容器內)

// Remember ids are case sensitive 
var type = 'A'; 

$('#txt' + type).show() // Show the current type 
    .siblings().hide(); // Hide all other elements 

小提琴:http://jsfiddle.net/garreh/4JkGm/

如果你的兄弟元素不總是你想要隱藏的類型,只需在它上面添加一個過濾器:

$('#txt' + type) 
    .show() // Show the current type 
    .siblings() 
    .filter(function() { 
     return (this.id.match(/^txt[A-C]$/)) 
    }).hide(); // Hide all other elements 

小提琴:http://jsfiddle.net/garreh/4JkGm/1/