简体   繁体   中英

I have two simple javascript slideshows on one page but the second one stops the first one working

Whats up guys, I'm having some problems with getting this code to work. The problem is that adding the second slideshow makes the first one stop working, it also causes the first slideshow when clicked to change the picture on the second slideshow. This is my first time trying any javascript. Both of the slideshows work on there own, I have looked into it and changed the line document.Lunch.src to have different names in the middle. I have also tried changing this line function slideshow() to function slideshow1() and function slideshow2() for both the scripts to see if that would work but I'm having no joy. I understand this question has been asked before as I have went through all similar question but they are from 2 and 3 years ago with no answers. Any help is well appreciated.

Here is my code

<SCRIPT type="text/javascript">
      var num = 1
      img1 = new Image ()
      img1.src = "Lunch2.jpg"
      img2 = new Image ()
      img2.src = "Lunch.jpg"

     function slideshow()
      {
            num = num + 1

            if (num == 3)
          {num = 1}

        document.Lunch.src=eval("img"+num+".src")
      }
</SCRIPT>

<SCRIPT type="text/javascript">
      var num = 1
      img1 = new Image ()
      img1.src = "Mail.jpg"
      img2 = new Image ()
      img2.src = "Mail2.jpg"

      function slideshow()
          {
                num = num + 1

               if (num == 3)
              {num = 1}

            document.Mail.src=eval("img"+num+".src")
          }
</SCRIPT>
</head> 

and here

    <IMG SRC = "Lunch2.jpg" NAME = "Lunch" BORDER = 3 alt = ""> 
    <p></p>
    <A HREF="JavaScript:slideshow()">Click for next picture</A>

    <IMG SRC = "Mail.jpg" NAME = "Mail" BORDER = 3 alt = "">
    <p></p>
    <A HREF="JavaScript:slideshow()">Click for next picture</A>

Your basic problem is one of redefining things. Since you do not namespace your slideshow function, when you define the second one, it replaces the first.

So, you wind up with two links that both call to the same slideshow method. And since the second definition has that method replace the source for document.Mail , that is what happens.

If you are wanting to just build up a pretty slideshow, you are best served by looking up how to do slideshows using any number of frameworks. I believe bootstrap is still popular. See here .

If you want to know more about namespacing javascript functions and variables. I'd recommend a javascript tutorial. I do not have a recommendation right off for this.

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