Home > Article > Web Front-end > How to change the src attribute in jquery
In jquery, you can use the attr() method to change the src attribute. This method is used to set or return the specified attribute value of the selected element. When the first parameter in the method is set to "src" , you can change the src attribute, the syntax is "specify element object.attr('src', new src attribute value)".
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
In jquery, the src attribute is mainly set through the attr() method to change the src attribute.
The following example explains how jquery changes the src attribute of the img tag.
Create a new html file, named test.html, to explain how jquery changes the src attribute of the img tag. Use the script tag to introduce the jquery.min.js file into the current page. Only when the file is successfully loaded can you use the jquery method.
Use the p tag to create an image using the img tag, and set the id of the img tag to myimg, which is mainly used to obtain the img object through this id below. Use the button tag to create a button with the name "Modify Image Address".
Bind the onclick event to the button button. When the button is clicked, the editsrc() function is executed.
In the js tag, create the editsrc() function. Within the function, use the $ symbol to obtain the img object through id(myimg), and use the attr() method to set the src attribute. For example, set the src image. The path is "images/3.jpg".
Open the test.html file in the browser and click the button to see the effect.
Summary:
1. Create a test.html file.
2. In the file, use the p tag, use the img tag to create a picture, and use the button tag to create a button to trigger the execution of the js function.
3. Create a function in the js tag. Within the function, use the $ symbol to obtain the img object, and use the attr() method to set the src attribute.
Note
In addition to setting the html tag, attr() can also get the attribute value of the html tag.
Recommended related video tutorials: jQuery video tutorial
The above is the detailed content of How to change the src attribute in jquery. For more information, please follow other related articles on the PHP Chinese website!