简体   繁体   中英

Using JavaScript onclick() to change an image

I want to be able to click on a li element for a side menu and it should make an image appear of change the current one to another.

This is the coding I have which should work but it doesn't and I dont know if I missed something or what is wrong.

<aside>
    <ul>
        <li onClick="document.getElementById('plantImg').src blanket">Blanket Flower</li>
        <li onclick="document.getElementById('plantImg').src rugosa">Hedge Rose</li>
        <li onclick="document.getElementById('plantImg').src bluestem">Little Bluestem</li>
    </ul>
</aside>

  <article>
     <figure>
     <img src="#" width="640" height="400" alt="" title="" id="plantImg"/>
         <figcaption>
            <script>
            /*
                Information on available plants
                including link to USDA website
            */
            document.write("<p>Plant choices for <a href= 'http://planthardiness.ars.usda.gov'> hardiness zones</a> 5a-6b</p>");// hardiness zones for Chicago and surrounding area

                var blanket = "images/blanket.jpg";
                var bluestem = "images/bluestem.jpg";
                var rugosa = "images/rugosa.jpg";
        </script>
        </figcaption>
     </figure>
  </article>

Thank you.

Yes you can do it like you wanted but no need for document.write .

 <aside> <ul> <li onClick="LoadImage(blanket)" style="cursor: pointer;" >Blanket Flower</li> <li onclick="LoadImage(rugosa)" style="cursor: pointer;" >Hedge Rose</li> <li onclick="LoadImage(bluestem)" style="cursor: pointer;">Little Bluestem</li> </ul> </aside> <article> <figure> <img src="#" width="640" height="400" alt="" title="" id="plantImg"/> <figcaption> <script> function LoadImage ( src_ ) { document.getElementById('plantImg').src = src_; } var blanket = "https://ckeditor.com/tmp/4.4.0/assets/js.png"; var bluestem = "https://tag.ruuvi.com/assets/images/ruuvi-tag-javascript.png"; var rugosa = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/ce/Unofficial_JavaScript_logo.svg/1024px-Unofficial_JavaScript_logo.svg.png"; </script> </figcaption> </figure> </article> 

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