2009-01-12 94 views
4

我有這樣的代碼:如何隱藏jQuery中的新元素?

var $msg = jQuery('<div></div>') 
    .hide() 
    .appendTo(document.body) 
; 
if ($msg.is(":hidden")) { 
    console.log("hidden"); 
} else { 
    console.log("visible"); 
} 

運行時,它記錄"hidden"在Firefox,但"visible"谷歌瀏覽器。這是一個錯誤,還是我做錯了什麼?

回答

4

你試過隱藏後追加到身體?

$(function() { 
    var $msg = jQuery('<div>hello</div>').appendTo(document.body).hide(); 
    if ($msg.is(":hidden")) { 
     console.log("hidden"); 
    } else { 
     console.log("visible"); 
    } 
}); // $() 

在這兩個瀏覽器上工作。

+0

什麼是外$()做? – 2009-01-12 08:10:19

+0

這是document.ready處理程序的簡寫形式。 – nickf 2009-01-12 08:21:06

0

as eed3si9n said,it was .hide() call is before the .appendTo() call。

我想我只是添加這個答案,因爲我發現了一個不同的方法也可以工作:

jQuery('<div></div>') 
    .css("display", "none") 
    .appendTo(document.body) 
; 

我完全不知道,如果它的工作原理是這樣的,但我想,添加元素隱藏它的DOM應該更快,因爲瀏覽器不需要渲染它?


對於那些你們誰是和我一樣,必須知道事情究竟是如何工作的最新情況:

爲jQuery.hide()的代碼 - 由我

hide: function(speed,callback){ 
    return speed ? 

     // this block of code won't be run, since speed will be undefined 
     this.animate({ 
      height: "hide", width: "hide", opacity: "hide" 
     }, speed, callback) : 

     // this is the relevant code 
     this.filter(":visible").each(function(){ 
      this.oldblock = this.oldblock || jQuery.css(this,"display"); 

      // you can see here that it merely sets the display to 'none' 
      this.style.display = "none"; 
     }).end(); 
} 

,並添加這裏的代碼爲:hidden選擇器:

hidden: function(a) { 
    return "hidden" == a.type      // <input type="hidden" /> 
     || jQuery.css(a, "display") == "none"  // style.display = none 
     || jQuery.css(a, "visibility") == "hidden"; // style.visibility = hidden 
} 

這並不能解釋爲什麼Chrome不是顯示元素爲隱藏雖然...