Let's take a specific look at the usage of attr:
attr (name): Gets the property value of the first matching element. This method makes it easy to get the value of a property from the first matching element. Returns undefined if the element does not have a corresponding property. where name is string. Below I use an IMG element to illustrate this usage:
Copy Code code as follows:
We can use attr to get the SRC attribute of the IMG element, as follows:
$ (function () {
var imgsrc = $ ("img"). attr (' src ');
alert (IMGSRC); Show A.gif
})
II, attr (key,value): Sets a property value for all matching elements. The key is a string property name, value is the object property, and is shown in the usage:
Copy Code code as follows:
in HTML file
Use this method to set the SRC attribute of img
$ (function () {
$ ("img"). attr (' src ', ' a.gif '); The file shows
})
Attr (properties): This is the best way to set many properties in batches in all matching elements. Note that if you want to set the class attribute of an object, you must use ' className ' as the property name. Or you can use the. addclass (Class) and. Removeclass (Class) directly.
Copy Code code as follows:
in file
$ (function () {
$ ("img"). attr ({src: ' a.gif ', title: ' This is a image ', ClassName: ' Filter '});
})
Display as
attr (Key, FN): Sets a computed property value for all matching elements. Instead of providing a value, a function is provided that evaluates the value of the function as the property value.
Copy Code code as follows:
File
$ (function () {
$ ("img"). attr (' title ', function () {return this.src}); Show
})
The above is a attr of some uses, the following is the use of removeattr remove so Minth meaning is removed, from each matching element to remove an attribute. Its specific use is:
Copy Code code as follows:
$ (function () {
$ ("img"). Removeattr (' title '); Show
})
The above introduces the basic use of attr and removeattr, in the actual work will also encounter some more complex applications, which requires us to master the basic use of the same time, a lot of summary and try other uses.