JQuery is a very popular JavaScript library through which you can easily operate and control various elements on web pages, including images.
In web development, one of the more common scenarios is the need to dynamically replace images after the user clicks on an element. At this time we can use the attr
function provided by JQuery to achieve this.
Let’s take a concrete example to see how to use JQuery to replace images.
Suppose there is a picture on our web page, and its HTML code is as follows:
<img src="./imgs/1.jpg" id="myImg">
What we want to do is to replace this picture with another picture when the user clicks a button. Suppose the path of another image is ./imgs/2.jpg
.
First, define a button element in HTML:
<button id="changeBtn">更换图片</button>
Then, use JQuery in JS to implement the function of replacing images:
$(document).ready(function(){ $("#changeBtn").click(function(){ $("#myImg").attr("src", "./imgs/2.jpg"); }); });
In the above code, we First, use $(document).ready()
to ensure that the web page is fully loaded before executing the subsequent code. Then, we bind the click
event of the button element, and the callback function will be triggered when the user clicks the button.
In the callback function, we called $("#myImg").attr("src", "./imgs/2.jpg")
, where, $("#myImg")
means selecting the picture element with ID myImg
, .attr("src", "./imgs/2.jpg")
means selecting The src
attribute of this element is set to ./imgs/2.jpg
, which is replaced by another image.
Through the above code, we have implemented a simple function of dynamically replacing pictures.
In addition to the above methods, you can also use JQuery's replaceWith
function to replace images. For specific usage, please refer to JQuery’s official documentation.
Summary:
JQuery provides a convenient API to help us operate and control various elements on web pages, including images. To replace an image, just set the corresponding attributes through the attr
function or the replaceWith
function.
The above is the detailed content of How to replace pictures with jquery. For more information, please follow other related articles on the PHP Chinese website!