Home >Web Front-end >Front-end Q&A >How to replace image path with jquery
In jquery, you can use the attr() method to replace the image path. This method can set or return the attributes and values of the selected element. Just set the first parameter in the brackets to the "src" attribute. , the second parameter can be set to the new image path, and the syntax is "image element object.attr("src", "replaced image path");".
The operating environment of this tutorial: windows10 system, jquery3.6.0 version, Dell G3 computer.
attr() method sets or returns the attributes and values of the selected element.
When this method is used to return an attribute value, the value of the first matching element is returned.
When this method is used to set attribute values, one or more attribute/value pairs are set for the matching element.
Syntax
Return the value of the attribute:
$(selector).attr(attribute)
Set the attribute and value:
$(selector).attr(attribute,value)
Use the function to set the attribute and value:
$(selector).attr(attribute,function(index,currentvalue))
Set multiple attributes and values:
$(selector).attr({attribute:value, attribute:value,...})
attribute specifies the name of the attribute.
value Specifies the value of the attribute.
function(index,currentvalue) specifies the function to return the attribute value to the collection
index - accepts the index position of the element in the collection.
currentvalue - Accepts the current attribute value of the selected element.
The example is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <script src="js/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("img").attr("src","1118.02.png"); }); }); </script> </head> <body> <img src="1118.01.png" alt="Pulpit Rock"> <br> <button>为图片替换路径</button> </body> </html>
Output result:
Video tutorial recommendation: jQuery video tutorial
The above is the detailed content of How to replace image path with jquery. For more information, please follow other related articles on the PHP Chinese website!