Next, let's take a look at the usage of attr:
1. attr (name): gets the attribute value of the First Matching Element. This method can be used to conveniently obtain the value of an attribute from the First Matching Element. If the element does not have a property, undefined is returned. Here, the name is string. I will use an img element to demonstrate this usage:
Copy codeThe Code is as follows:
//
// We can use attr to obtain the src attribute of the img element. The usage is as follows:
$ (Function (){
Var imgSrc = $ ("img"). attr ('src ');
Alert (imgSrc); // displays a.gif
})
2. attr (key, value): sets an attribute value for all matching elements. Key is the string attribute name, and value is the object attribute value. Usage Demonstration:
Copy codeThe Code is as follows:
// Html file
// Use this method to set the src attribute of img
$ (Function (){
$ ("Img"). attr ('src', 'a.gif '); //
})
3. attr (properties): This is the best way to set many attributes in batches among all matching elements. Note: To set the class attribute of an object, you must use 'classname' as the attribute name. Or you can directly use. addClass (class) and. removeClass (class ).
Copy codeThe Code is as follows:
// File
$ (Function (){
$ ("Img"). attr ({src: 'a.gif ', title: 'This is a image', className: 'filter '});
})
// Display as
4. attr (key, fn): sets a calculated attribute value for all matching elements. Instead of providing a value, a function is provided. The value calculated by this function is used as the attribute value.
Copy codeThe Code is as follows:
//
$ (Function (){
$ ("Img "). attr ('title', function () {return this. src}); // display
})
The above describes some usage of attr. The following is the usage of removeAttr. Therefore, the meaning of removal is to delete an attribute from each matching element. Its specific usage is:
Copy codeThe Code is as follows:
//
$ (Function (){
$ ("Img"). removeAttr ('title'); // display
})
The above describes the basic usage of attr and removeAttr, and some more complex applications will be encountered in actual work. This requires us to master the basic usage while, summarize and try other methods.