2013-01-15 100 views
5

我在stackoverflow中找到了此腳本。Div風格未定義(Javascript)

function showhide(id){ 
     if (document.getElementById) { 
      var divid = document.getElementById(id); 
      var divs = document.getElementsByClassName("hideable"); 
      for(var div in divs) { 
      div.style.display = "none"; 
      } 
      divid.style.display = "block"; 
     } 
     return false; 
     } 

<a href="#" onclick="showhide('features');" >features</a> 
<a href="#" onclick="showhide('design');" >design</a> 
<a href="#" onclick="showhide('create');" >create</a> 

<div class="hideable" id="features">Div 1</div> 
<div class="hideable" id="design">Div 2</div> 
<div class="hideable" id="create">Div 3</div> 

但它說,div.style未定義。爲什麼? :)

+0

在哪些瀏覽器? –

+0

你正在使用哪個瀏覽器? – Pranav

+0

最新FF,17.0.1 – user1632298

回答

-1

確保一切都在你for-in迴路的元素是DOM元素。這是一個很好的做法,過濾for-in循環用hasOwnProperty()

 for(var div in divs) { 
      if (divs.hasOwnProperty(div)) { 
       if (div && div.style) { 
        div.style.display = "none"; 
       } 
      } 
     } 
3
for(var i = 0; i < divs.length; i++) { 
     divs[i].style.display = "none"; 
     } 

編輯:爲循環通過對象屬性用於循環

1

更換

for(var div in divs) { 

for(var i=0; i<divs.length;i++) { 
    var div = divs[i]; 

divs,的getElementsByClassName的結果,是不是一個真正的數組,但一個節點列表,陣列狀物體和你迭代上它的屬性,而不是它的元件。

5

你不應該一個for-in循環的使用。

document.getElementsByClassName('someClass') 

返回NodeList,不從Array.prototype繼承,但它在某些方面類似。這是一個節點列表,就像名稱所示。這意味着它有一個length性能,應該只使用訪問:

var myElements = document.getElementsByClassName('yourClass'); 
for (var i = 0, ii = myElements.length; i < ii; i++) { 
    console.dir(myElements[i].style); 
}; 

這裏是你應該如何真正隱藏的元素。

/** 
* Shows or hides an element from the page. Hiding the element is done by 
* setting the display property to "none", removing the element from the 
* rendering hierarchy so it takes up no space. To show the element, the default 
* inherited display property is restored (defined either in stylesheets or by 
* the browser's default style rules.) 
* 
* Caveat 1: if the inherited display property for the element is set to "none" 
* by the stylesheets, that is the property that will be restored by a call to 
* showElement(), effectively toggling the display between "none" and "none". 
* 
* Caveat 2: if the element display style is set inline (by setting either 
* element.style.display or a style attribute in the HTML), a call to 
* showElement will clear that setting and defer to the inherited style in the 
* stylesheet. 
* @param {Element} el Element to show or hide. 
* @param {*} display True to render the element in its default style, 
* false to disable rendering the element. 
*/ 
var showElement = function(el, display) { 
    el.style.display = display ? '' : 'none'; 
}; 

var myElement = document.getElementById('someID'); 
showElement(myElement, false);// it should now be hidden.