【问题标题】:jQuery not creating area tagsjQuery没有创建区域标签
【发布时间】:2009-11-20 00:25:35
【问题描述】:

我正在尝试使用 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 的调用来使它变得更有趣,但这很烦人,我想了解这种行为。

【问题讨论】:

    标签: javascript jquery imagemap


    【解决方案1】:

    &lt;area /&gt; 元素仅在图像映射中定义(即&lt;map&gt; 元素)。所以基本上以下是失败的(因为这是 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
    

    【讨论】:

    • +1 不要期望 jQuery 总是做正确的事,不管它在 SO 上不断的助推器说什么。
    • 如果他试图附加$area(因为它只有内容)它不会包含&lt;map&gt;,那么为什么不在附加之前用地图标签包裹$area呢?
    • @fudgey: 因为一个&lt;map&gt; 可以包含多个&lt;area /&gt; 元素。
    猜你喜欢
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 2011-09-14
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多