2009-11-20 60 views
4

我試圖使用jQuery動態創建圖像映射,我遇到了一個奇怪的現象:jQuery的不作成區域標籤

alert($('<area />').size());       // 1 
alert($('<area shape="circle" />').size());   // 0 
alert($('<area />').attr("shape", "circle").size()); // 1 

換句話說,我不可能全部創建區域標籤立刻;如果我說

$('<area shape="circle" coords="50,25,4" href="#" alt="foo" />') 

然後什麼也沒有創建。然而,如果我逐漸做到這一點,它就會奏效,例如

$('<area />') 
    .attr("shape", "circle") 
    .attr("coords", "50,25,4") 
    .attr("href", "#") 
    .attr("alt", "foo"); 

我不知道這是爲什麼,因爲我可以創建各種其他元素的屬性和內容,例如,

$('<div id="foo" />') 
$('<div id="bar">Hello World!</div>') 

所以我不清楚爲什麼這不起作用。這並不是那麼重要,因爲我可以通過將電話連接到attr來使它失敗,但這很煩人,我想了解這種行爲。

回答

4

<area />元素僅在圖像映射(即<map>元素)內定義。所以基本上是失敗(因爲這是jQuery是與您的標記做)以下:

var div = document.createElement('div'); 
div.innerHTML = '<area shape="circle" coords="50,25,4" href="#" alt="foo" />'; 
return div.childNodes; // this is empty, as the browser didn't allow 
         // the <area /> element inside the <div> element 

這只是其中的一件事情顯然是巨大的jQuery並沒有佔到一個(還)。與此同時嘗試:

var $area = $(
    '<map><area shape="circle" coords="50,25,4" href="#" alt="foo" /></map>' 
).contents(); 

// $area is the jQuery object for the newly created <area /> tag 

$area.attr('coords'); // "50,25,4" 

// etc 
+2

+1不要指望jQuery總是做正確的事情,不管它在這裏說的不斷推動者如何說。 – bobince 2009-11-20 00:53:14

+0

如果他試圖添加'$ area'(因爲它只包含內容),它將不包含'',那麼爲什麼不在附加之前用'map'標記'$ area'呢? – Mottie 2009-11-20 03:42:27

+1

@fudgey:因爲「」可以包含多個「」元素。 – 2009-11-20 11:04:41