开发者

jQuery element constructor differs from using attr

jQuery 1.4 added a shorthand way for constructing new DOM Elements and filling in some of their attributes:

jQuery( html, props )

html: A string defining a single, standalone, HTML element (e.g. or ).

props: A map of attributes, events, and methods to call on the newly-created element.

But, I just noticed this strangeness (with jQuery 1.5.1):

>>> $("<img />", { 开发者_如何学编程height: 4 })[0].height
0
>>> $("<img />").attr({ height: 4 })[0].height
4

So, they are some differences between the shorthand and the longer way..! Is this a bug or is it intentional? Are there any other ones with similar behaviour which I should watch out for?


From the docs:

As of jQuery 1.4, the second argument can accept a map consisting of a superset of the properties that can be passed to the .attr() method. Furthermore, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data, width, height, or offset.

So basically the snippet is not equivalent to $("<img />").attr({ height: 4 }) but to $("<img />").height(4) and the html it evaluates to is <img style="height: 4px" /> - hence the returned 0.


The short way should be :

$("<img />", { height: 4 }).height();


The difference is setting the attr will add a height attribute, the other forms set the height style property. So the shorthand version sets the style rather than the height attribute:

    $("<img />", { height: 4 });
    // creates <img style="height:4px;">


    $("<img />").height(4);
    // creates <img style="height:4px;">


    $("<img />").attr({height: 4});
    // creates <img height="4">

This is the case whether you append the element into the DOM or not (with jquery 1.4.4 and 1.5.1). Apologies if I'm restating something already covered in the comments.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜