jQuery in Action

Manipulating element properties and attributes
53
this, let's amend the
<img>
element of our previous example with a custom
markup attribute (highlighted in bold):
<img id="myImage" src="image.gif" alt="An image" class="someClass"
title="This is an image" custom="some value"/>
Note that we have added a custom attribute, unimaginatively named
custom
, to
the element. We can retrieve that attribute's value, as if it were any of the standard
attributes, with
$("#myImage").attr("custom")
WARNING
Using a nonstandard attribute name such as
custom
, although a com-
mon sleight-of-hand trick, will cause your markup to be considered
invalid; it will fail validation testing. This may have implications for
accessibility, as well as for parsing by programs that expect your site to be
written in valid
HTML
or
XHTML
.
Attribute names are not case sensitive in
HTML
. Regardless of how an attribute
such as
title
is declared in the markup, we can access (or set, as we shall see)
attributes using any variants of case:
Title
,
TITLE
,
TiTlE
, or any other combina-
tions are all equivalent. In
XHTML
, even though attribute names must be lower-
case in the markup, we can retrieve them using any case variant.
At this point you may be asking, "Why deal with attributes at all when access-
ing the properties is so easy (as seen in the previous section)?"
The answer to that question is that the jQuery
attr()
command is much more
than a wrapper around the JavaScript
getAttribute()
and
setAttribute()
meth-
ods. In addition to allowing access to the set of element attributes, jQuery pro-
vides access to some commonly used properties that, traditionally, have been a
thorn in the side of page authors everywhere due to their browser dependency.
This set of normalized-access names is shown in table 3.1.
Table 3.1 jQuery
attr()
normalized-access names
Normalized name
Source name
class
className
cssFloat
styleFloat
for IE, cssFloat for others (when used with .css)
float
styleFloat
for IE, cssFloat for others (when used with .css)
for
htmlFor
continued on next page


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.