Jquery method to change img src attribute: 1. Use attr() attribute, syntax "$("img").attr("src","image file address")"; 2. Use prop () method, syntax "$("img").prop("src","image file address")".
The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.
How does jquery change the src attribute of img
##Method 1: Use attr() attribute## The #attr() method sets or returns the attribute value of the selected element.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.6.1.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("img").attr("src","img/2.jpg"); }); }); </script> </head> <body> <img id="img" src="img/1.jpg" style="max-width:90%"/ alt="How to change the src attribute of img in jquery" ><br><br><br> <button>更改img src属性值(换图)</button> </body> </html>
The prop() method sets or returns the attributes and values of the selected element .
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.6.1.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("img").prop("src","img/3.jpg"); }); }); </script> </head> <body> <img id="img" src="img/1.jpg" style="max-width:90%"/ alt="How to change the src attribute of img in jquery" ><br><br><br> <button>更改img src属性值(换图)</button> </body> </html>
[Recommended learning:
jQuery video tutorial, web front-end introductory video]
The above is the detailed content of How to change the src attribute of img in jquery. For more information, please follow other related articles on the PHP Chinese website!