简体   繁体   中英

onload event event javascript not responding

Javascript code:

<script type="text/javascript">
  function react() {
     document.getElementById("img").src = second.jpg
  }
</script>

Html Page:

<div style="width:170px;height:160px;border:2px solid blue">
 <img src="first.jpg" style="width:inherit;height:inherit" id="img" onload="setTimeout('react()', 15000)"/>
</div>

Please the The image in the does not change as it is meant to change from first.jpg to second.jpg in 15000 milliseconds as set by the setTimeout() function

second.jpg means "The jpg property of the second object" (which is hasn't been mentioned before so it will throw a reference error).

You need to use a string literal: "second.jpg" .

second.jpg should be in quotes,

<script type="text/javascript">
 function react() {
  document.getElementById("img").src = 'second.jpg';
 }
</script>

The string value must be between quotes. Also, you should ad onload event in <body> tag.

document.getElementById("img").src = 'second.jpg';

second.jpg should be quoted and the setTimeout accepts a function reference:

<script type="text/javascript">
  function react() {
     document.getElementById("img").src = "second.jpg"
  }
</script>

<div style="width:170px;height:160px;border:2px solid blue">
 <img src="first.jpg" style="width:inherit;height:inherit" id="img" onload="setTimeout(react, 15000);"/>
</div>

The IMG tag does nopt support the onload attribute. Move it to the body tag:

<body onload="setTimeout('react()', 15000)">
  <div style="width:170px;height:160px;border:2px solid blue">
   <img src="first.jpg" style="width:inherit;height:inherit" id="img" />
  </div>
</body>

Also, enclose second.jpg in your react function in quotes.

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