Bu betiği stackoverflow içinde buldum.Div stili tanımsız (Javascript)
Ama diyor ki, div.style tanımsız. Niye ya?
Bu betiği stackoverflow içinde buldum.Div stili tanımsız (Javascript)
Ama diyor ki, div.style tanımsız. Niye ya?
for-in
döngüdeki tüm öğelerin DOM öğeleri olduğundan emin olun. Bu hasOwnProperty()
ile for-in
döngü filtre iyi bir uygulamadır:
for(var div in divs) {
if (divs.hasOwnProperty(div)) {
if (div && div.style) {
div.style.display = "none";
}
}
}
for(var i = 0; i < divs.length; i++) {
divs[i].style.display = "none";
}
DÜZENLEME: nesne özellikleri döngü için kullanılan halkalarla için
for(var div in divs) {
yerine
for(var i=0; i<divs.length;i++) {
var div = divs[i];
sonucu,
divs
, bir dizi değil, NodeList, bir dizi benzeri bir nesne ve kendi özellikleri üzerinde değil, kendi öğeleri yineliyordu.
Bunun için asla bir giriş döngüsü kullanmamalısınız.
document.getElementsByClassName('someClass')
Array.prototype
devralan olmayan bir NodeList, döner, ancak bazı açılardan benzer. İsminin söylediği gibi, düğümlerin bir listesi.
var myElements = document.getElementsByClassName('yourClass');
for (var i = 0, ii = myElements.length; i < ii; i++) {
console.dir(myElements[i].style);
};
Ve burada aslında bir öğe gizlemek nasıl olduğunu: Bu da length
özelliği vardır ve sadece kullanarak erişilebilir gerektiği anlamına gelir.
/**
* 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.
Hangi tarayıcıda? –
hangi tarayıcıyı kullanıyorsunuz? – Pranav
En son FF, 17.0.1 – user1632298