We often need to change node attributes, content, and text, so we need to use several functions here.
1 attribute
Here we see an attr() function, which has four forms. Attr(name) is to get a selected attribute value, attr(properties)attr (key, value) attr (key, fn) is to assign a value to an attribute
What I want to say here is that there is such a design in Jquery. The same function is used to obtain the value of an object and assign a value to an object. Use fn(name) to assign a value to an object, and use fn(name, value) to assign a value to an object.
First look at how attr(name) gets an attribute value
We have
In this way we hope to get the value of stc in img. First we use the selector to select this img $ ("img") gets the node above, and then we use attr() to get the value of src: $("img").attr("src")
In this way we get the value of 1.jpg
Now we want to replace the image 1.jpg with the image 2.jpg: just use $("img").attr("src","2.jpg"), this is fn ( name, key), of course we know that in JavaScript, for example, onclick may be a function. Of course, other attributes can also be functions, so our key can also be a function $("img").attr("src ”, function(){return '3.jpg'}), this is the second form, which is actually the same as the first one
The third form, that is, attr (properties) is in josn format. Name: value is used to assign attributes. In Jquery, this method is very commonly used, and the structure is also very clear
For example, if we want to set the alt and src of img, we can directly write it as $("img").attr( {src:”4.jpg”,alt:”Description”})
Generally when we build a system, we need to add, modify and delete. We have talked about the first two before, so how to delete an attribute?
Here we need to use removeAttr(name), which is easy to understand. It is just the opposite of arrt(name). One is to get an attribute, and the other is to delete it. An attribute $("img").removeAttr("alt")
Okay, let's summarize several functions for operating attributes
Search: $("img").attr("src") Find the value of src
Add/modify $(“img”).attr(“src”,”2.jpg”) $(“img”).attr(“src”,function(){return “2 .jpg"}) $("img").attr({src:"2.jpg"})
Delete $("img").removeAttr("src")
2 css class
When we need to add a css style to a node such as