2009-11-20 27 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