【发布时间】:2011-05-17 21:15:55
【问题描述】:
jQuery 1.4 docs 描述了如何使用 jQuery 从提供的 HTML 字符串和属性集动态创建 DOM 元素。例如:
var d = $('<div/>', {id:'foo', className:'bar'});
d; // => [<div id="foo" class="bar"></div>]
d.attr('id'); // => "foo"
d.attr('class'); // => "bar"
这太棒了;但是,在对具有宽度和高度的图像使用此快捷方式时,似乎存在错误。它设置 CSS 样式,而不是设置属性(如 attr() function 所暗示的那样):
var x = $('<img/>', {width:10, height:20});
x; // => [<img style="width: 10px; height: 20px; ">]!!!
x.attr('width'); // => 0!!!
x.attr('height'); // => 0!!!
这更加令人困惑,因为当从构造函数中给定一个新图像时,jQuery 的行为符合预期:
var y = $(new Image(10, 20));
y; // => [<img width="10" height="20">]
y.attr('width'); // => 10
y.attr('height'); // => 20
这只是 jQuery 1.4.2 中的错误还是出于某种原因的预期行为?
【问题讨论】:
-
离题,但请注意
class:'bar'会在某些浏览器中中断。你应该做'class':'bar'或className:'bar'。 -
@patrick dw:谢谢,我会编辑我的答案以避免混淆。
标签: jquery