Home >Web Front-end >Front-end Q&A >Can jquery get the src attribute of an image?
jquery can get the src attribute of the image. Obtaining method: 1. Use attr() to get the src attribute of the img picture element, the syntax is "$(img).attr("src")"; 2. Use prop() to get the first matching img picture element src attribute, the syntax is "$(img).prop("src")".
The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.
In jquery, you can use two methods to get the attributes of an element:
attr()
prop()
Method 1. Use attr() to get the src attribute of the image
attr() method can return the Select the attribute value of the element
Syntax:
元素对象.attr("属性名")
You only need to get the specified img element object and use the attr("src")
method. You can get the src attribute of the image
Example: Get the img src attribute value, which is the image address
<!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() { var img=$("img").attr("src"); console.log("src属性值为: "+img) }); }); </script> </head> <body> <img id="img" src="img/2.jpg" style="max-width:90%"/ alt="Can jquery get the src attribute of an image?" ><br><br> <button>获取img src属性值(图片地址)</button> </body> </html>
2. Use prop() to get the src attribute of the image
The prop() method can return the attribute value of the selected element, and will return the attribute value of the first matching element.
Syntax:
元素对象.prop("属性名")
You only need to get the specified img element object and use the prop("src")
method to obtain it The src attribute of the image
Example: Get the img src attribute value, which is the image address
<!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() { var img=$("img").prop("src");; console.log("src属性值为: "+img) }); }); </script> </head> <body> <img id="img" src="img/2.jpg" style="max-width:90%"/ alt="Can jquery get the src attribute of an image?" ><br><br> <button>获取img src属性值(图片地址)</button> </body> </html>
[Recommended learning :jQuery video tutorial、web front-end video】
The above is the detailed content of Can jquery get the src attribute of an image?. For more information, please follow other related articles on the PHP Chinese website!