简体   繁体   中英

Javascript onClick image change

This is my first post here, so please bear with the formatting.
What I basically wanted to do was switch from an event to another with an onClick event.

It worked, so I wanted to add a loading image in between the 2 images.

function gerrard(details) {
   var a=0;
   details.src='file://macintosh%20hd/Users/megaestore/Desktop/voting/loading.gif';
   while (a<1000000000) {
      a=a+1;
   }
   details.src='file://macintosh%20hd/Users/megaestore/Desktop/voting/gerrard.jpg';
}

It just waits for a while before changing the image, but the loading.gif does not load at all. On clicking the button, there is a delay, while the original image stays, and then the gerrard.jpg opens.

WHY IS THE LOADING.GIF BEING IGNORED ??

HTML, not really required here,but still

<img src="gerrard.jpg" id="details" name="details">
<br/>
<form id="change">
<input type="button" id="change" onClick="gerrard(details)" value="Gerrard"/>

PS- I'm new to JavaScript.

JavaScript is async language so if you want to set a delay you should use setTimeOut function instead of loop (cause loop will execute parallel with the following code) use like this:

function gerrard(details) {
details.src='file://macintosh%20hd/Users/megaestore/Desktop/voting/loading.gif';
//here we waiting fo 5 secs, and then changing image
setTimeout(
    function(){details.src='file://macintosh%20hd/Users/megaestore/Desktop/voting/gerrard.jpg';}, 5000) 
}

In your case:

function gerrard(details) {
var a=0;
details.src='file://macintosh%20hd/Users/megaestore/Desktop/voting/loading.gif';
while (a<1000000000) {
   a=a+1;
}
 //while loop still going execute the code go next and changing image
details.src='file://macintosh%20hd/Users/megaestore/Desktop/voting/gerrard.jpg';
}

So if you want to do it without settimeout, and with loop you need to add changing image inside loop:

function gerrard(details) {
var a=0;
details.src='file://macintosh%20hd/Users/megaestore/Desktop/voting/loading.gif';
while (a<1000000000) {
  a=a+1;
  if (a==999999999)
  details.src='file://macintosh%20hd/Users/megaestore/Desktop/voting/gerrard.jpg';
  }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM