2012-04-08 30 views
3

我不知道是否有人可以解釋爲什麼在第一次創建的div背景顏色不會工作,它在第二個例子中。jQuery div隨着背景顏色的飛行

$("<div/>", { 
width:300, 
height:400, 
backgroundColor:"#425412", //background-color does not work 
text: "hello there" 
}).appendTo("body"); 

注意:如果沒有background-color屬性,div將被創建。

// works as defined including background-color 
$("<div style='width:300; height:400; background-color:#425412;'>hello there</div>").appendTo("body"); 

第一種方法是否有限制?

回答

5

您需要使backgroundColor屬性成爲css對象的關鍵字。

$("<div/>", { 
    width:300, 
    height:400, 
    css: { 
     backgroundColor:"#425412" 
    }, 
    text: "hello there" 
}).appendTo("body"); 

jsFiddle

+0

你讓我難以置信+1 – Starx 2012-04-08 06:25:33

+0

真的......有趣。謝謝,對我來說這是一個新的.. :-) – Daniel 2012-04-08 06:30:26

+0

@Daniel:在[jQuery文檔](http://api.jquery.com/jQuery/#jQuery2)中描述得相當晦澀:*從jQuery 1.4開始,jQuery()的第二個參數可以接受由可以傳遞給.attr()方法的屬性的超集組成的映射。此外,可以傳入任何事件類型,並且可以調用以下jQuery方法:val,css,html,text,data,width,height或offset。名稱「類」必須在地圖中引用,因爲它是JavaScript保留字,並且「className」不能使用,因爲它不是正確的屬性名稱。* – Spoike 2012-04-08 07:02:09