Home > Web Front-end > Front-end Q&A > How to change the src attribute of img in jquery

How to change the src attribute of img in jquery

青灯夜游
Release: 2022-12-16 16:46:50
Original
13223 people have browsed it

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")".

How to change the src attribute of img in jquery

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>
Copy after login

How to change the src attribute of img in jquery

Method 2: Use the prop() method

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>
Copy after login

How to change the src attribute of img in jquery[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template