Setting method: 1. Use the src attribute of the element object, the syntax "img element object.src="attribute value""; 2. Use the setAttribute() method, the syntax "img element object.setAttribute("src ","Attribute value")".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript sets img src value
Method 1: Use the src attribute of the element object
<!DOCTYPE html> <html> <body> <img src="img/1.jpg" style="max-width:90%" / alt="How to set img src value in javascript" > <p id="demo">点击按钮来改变img标签的内容。</p> <button onclick="myFunction()">试一下</button> <script> function myFunction() { var img = document.getElementsByTagName("img")[0]; img.src = "img/2.jpg"; } </script> </body> </html>
Rendering:
Method 2: Use the setAttribute() method
setAttribute() method to add the specified attribute , and assign the specified value to it. If this specified property already exists, the value is only set/changed.
<!DOCTYPE html> <html> <body> <img src="img/1.jpg" style="max-width:90%" / alt="How to set img src value in javascript" > <p id="demo">点击按钮来改变img标签的内容。</p> <button onclick="myFunction()">试一下</button> <script> function myFunction() { var img = document.getElementsByTagName("img")[0]; img.setAttribute("src","img/3.jpg"); } </script> </body> </html>
Rendering:
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to set img src value in javascript. For more information, please follow other related articles on the PHP Chinese website!