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

How to change the src attribute of img in jquery

青灯夜游
青灯夜游Original
2022-03-03 15:41:5213188browse

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>

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>

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!

Statement:
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