2013-07-22 159 views
0

我有一個javascript代碼,當單擊鏈接時,它可以顯示和隱藏頁面的分區。jquery顯示和隱藏

function shoh(id) { 

    if (document.getElementById) { // DOM3 = IE5, NS6 
     if (document.getElementById(id).style.display == "none"){ 
      $(id).fadeIn();  
     } else { 
      $(id).hide(); 
     } 
    } else { 
     if (document.layers) { 
      if (document.id.display == "none"){ 
       document.id.display = 'block'; 
      } else { 
       document.id.display = 'none'; 
      } 
     } else { 
      if (document.all.id.style.visibility == "none"){ 
       document.all.id.style.display = 'block'; 
      } else { 
       document.all.id.style.display = 'none'; 
      } 
     } 
    } 
} 

然而現在,當我加入jQuery的淡入不起作用並隱藏,而不是使用document.getElementById方法。爲什麼?

+0

你有沒有添加了jQuery庫加載這一頁? – Dom

+1

爲什麼你在2013年使用2000年的這個可怕的兼容性代碼?你甚至不需要在這裏使用jQuery,所有*瀏覽器今天都支持'getElementById'。 – Jon

回答

5

爲了通過jQuery選擇一個元素,你必須使用selector syntax這意味着將#添加到id。因此,改變

$(id).fadeIn(); 

$("#" + id).fadeIn(); 
+0

您的傳奇!非常感謝你 – user2166538

+0

顯然不能接受8分鐘 – user2166538

+0

@ user2166538,謝謝考慮 – Satpal

0

試試這個:

function shoh(id) { 
    var el = $('#' + id); 
    if (el.is(':visible')) { 
     el.hide(); 
    } else { 
     el.fadeIn(); 
    } 
} 
0

由於jQuery的爲你工作,你會不會寫代碼,跨瀏覽器。

所以,簡單地

var $el = $('#'+id); // <-- this is the main key :-) 

if ($el.css('display') == "none"){ 
     $el.fadeIn();  
} else { 
     $el.hide(); 
} 
0

你可以只聲明爲一個變量,然後在jQuery選擇把它包裝:

var $el = $(document.getElementById(id)); 
// if 
$el.fadein(); 
//else 
$el.hide(); 

jsFiddle

+0

$($ el)是無用的,因爲$ el已經是jquery對象。 :-) –