How to Use arrays to create images and switch js code in the previous article, we talked about the specific operations of arrays in js. For details, see (Summary of various operations of Js on Array ), I will not explain it in detail here. Today, the main purpose is to use arrays to perform simple left/right switching of images.
The steps for switching images in this article are as follows:
Step 2: simple layout and basic display style design;
Step 2: Get related elements through js;
Step 2: Store Image URLs and corresponding text descriptions through arrays;
Step 2: initialization: including image initialization, display of image numbers, and initialization of corresponding text;
Step 2: click the button to switch the image and write the corresponding function, which is actually a simple application of arrays.
Implementation Code:
Image Switching Script window. onload = function () {var oPrev = document. getElementById ("prev"); var oNext = document. getElementById ("next"); var oText = document. getElementById ("text"); var oNum = document. getElementById ("num"); var oImg = document. getElementById ("img1"); var arrUrl = ['images/1.jpg ', 'images/2.jpg', 'images/3.jpg ', 'images/4.jpg']; var arrText = ['text 1', 'text 2', 'text 3', 'text 4']; // initialize var num = 0; function fnTab () {oNum. innerHTML = num + 1 + '/' + arrText. length; oImg. src = arrUrl [num]; oText. innerHTML = arrText [num];}; fnTab (); oPrev. onclick = function () {num --; if (num =-1) {num = arrUrl. length-1;} fnTab () ;}; oNext. onclick = function () {num ++; if (num = arrUrl. length) {num = 0;} fnTab () ;};}; script <>
Loading images ......
Counting ......
This example is very simple. It mainly involves reading and writing arrays and html attributes. It should be noted that when we click the next image to the last image or click the previous image to the first image, we need to set the specific value change, no = otherwise it will cross the border, then there is no problem with pictures, numbers, and corresponding content.