简体   繁体   English

Ajax、JQuery 和 JavaScript - 图片未加载//显示

[英]Ajax, JQuery & JavaScript - Pictures Not Loading//Showing

I'm trying to create a photo gallery using Ajax and JQuery in Javascript.我正在尝试使用 Javascript 中的 Ajax 和 JQuery 创建照片库。 I have a folder created in VSC called "images" and inside it I have my 5 chosen images.我在 VSC 中创建了一个名为“images”的文件夹,里面有我选择的 5 张图片。 Unfortunately, once I click the "next" and "previous" buttons, the images are not showing.不幸的是,一旦我单击“下一个”和“上一个”按钮,图像就不会显示。 In the console it says that the photos are undefined.在控制台中,它说照片未定义。 Any ideas as to how I can solve this issue?关于如何解决这个问题的任何想法? I would greatly appreciate the help as I'm quite new to all this: Below is my HTML and JS code我非常感谢您的帮助,因为我对这一切都很陌生:下面是我的 HTML 和 JS 代码

    <div id="content">
        <div id="picture">
            <img id="pic" src="images/image1.jpg">
        </div>
    </div>

    <div id="buttons">
        <button id="previous" type="button" class="BUTTON_AUJ">Previous</button>
        <button id="update" type="button" class="BUTTON_AUJ">Update</button>
        <button id="next" type="button" class="BUTTON_AUJ">Next</button>
    </div>
'use strict';
$(document).ready(function () {
    var max_index = null, min_index = 0;
    var timeID = null;
    var index = 0;
    var files = [];
    function changePicture(pics){
        $("#pic").attr("src", "images/" + pics);
        $("#picture").hide().fadeIn("slow");
    } 
   

    function loadImages() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState === 4) {
                files = JSON.parse(this.responseText).files;
                max_index = files.length - 1;
                changePicture(files[index]);
                rotating(files[min_index]);
            }
        };
        xhttp.open("GET", "file.html", true);
        xhttp.send();
    }

    function nextPicture(){
        if (index < max_index)
            index++;
        else 
            index = min_index;
        changePicture(files[index]);
        rotating(files[index]);
    }
    function previousPicture() {
        if (index > min_index)
            index--;
        else
            index = max_index;
        changePicture(files[index]);
        rotating(files[index]);
    }
    function rotating(filename){
        var interval = filename.split("_")[1].replace(".jpg", "") * 1000;
        if (timeID) {
            clearTimeout(timeID);
            timeID = null;
        }
        timeID = setTimeout(nextPicture, interval);
    }
    function main(){
        loadImages();
    }
    main();

    $("#next").click(function () {
        nextPicture();
    });
    $("#previous").click(function () {
        previousPicture();
    });
    $("update").click(function(){
        index = 0;
        loadImages();
    });
}); 

Consider the following example.考虑以下示例。

Fiddle: https://jsfiddle.net/Twisty/0ku35r7b/小提琴: https://jsfiddle.net/Twisty/0ku35r7b/

HTML HTML

<div id="content">
  <div id="picture">
    <img id="pic" src="https://dummyimage.com/480x340/ccc/000.jpg&text=Image0">
  </div>
</div>

<div id="buttons">
  <button id="previous" type="button" class="BUTTON_AUJ">Previous</button>
  <button id="update" type="button" class="BUTTON_AUJ">Slide Start</button>
  <button id="next" type="button" class="BUTTON_AUJ">Next</button>
</div>

JavaScript JavaScript

 $(function() {

  var testData = {
    files: [
      "https://dummyimage.com/480x340/ccc/000.jpg&text=Image0",
      "https://dummyimage.com/480x340/ccc/000.jpg&text=Image1",
      "https://dummyimage.com/480x340/ccc/000.jpg&text=Image2",
      "https://dummyimage.com/480x340/ccc/000.jpg&text=Image3"
    ]
  };

  function getImages() {
    var myImages = [];
    $.post("/echo/json", {
      json: JSON.stringify(testData)
    }, function(results) {
      $.each(results.files, function(i, image) {
        myImages.push(image);
      });
    });
    $("#picture").data("index", 0);
    return myImages
  }

  function changePicture(index) {
    console.log("Change to Picture " + index);
    var current = $("#picture img");
    current.hide().attr("src", $("#picture").data("images")[index]).fadeIn();
  }


  function nextPicture() {
    console.log("Next");
    var index = $("#picture").data("index");
    console.log("Current Index: " + index);
    if (++index >= $("#picture").data("images").length) {
      index = 0;
    }
    console.log("Next Index: " + index);
    changePicture(index);
    $("#picture").data("index", index);
  }

  function previousPicture() {
    console.log("Previous");
    var index = $("#picture").data("index");
    console.log("Current Index: " + index);
    if (--index < 0) {
      index = $("#picture").data("images").length - 1;
    }
    console.log("Previous Index: " + index);
    changePicture(index);
    $("#picture").data("index", index);
  }

  function startRotation() {
    var interval = 3000;
    console.log("Start Rotation", interval);
    $("#picture").data("interval", setInterval(nextPicture, interval));
  }

  function stopRotation() {
    console.log("Stop Rotation");
    clearInterval($("#picture").data("interval"));
  }

  function main() {
    console.log("INIT");
    $("#picture").data("images", getImages());
    console.log($("#picture").data("images"));
    console.log($("#picture").data("index"));
  }
  main();

  $("#next").click(nextPicture);
  $("#previous").click(previousPicture);
  $("#update").click(function() {
    if (!$(this).data("rotate")) {
      startRotation();
      $(this).html("Slide Stop").data("rotate", true);
    } else {
      stopRotation();
      $(this).html("Slide Start").data("rotate", false);
    }

  });
});

This example makes use of JSFiddles Async options.此示例使用 JSFiddles 异步选项。 Your AJAX Code will be different.您的 AJAX 代码会有所不同。 I suggest something like:我建议类似:

$.getJSON("file.json", function(results){ })`

This flushes out the functions a bit more and uses the .data() feature to store images, index, intervals in the attributes of the elements.这会更多地刷新函数,并使用.data()功能在元素的属性中存储图像、索引、间隔。 This makes them more available to different functions.这使它们更适用于不同的功能。 There is nothing wrong with storing them in Global variables.将它们存储在全局变量中没有任何问题。 If you have more than one, storing their indexes and Image lists with them makes them easy to access.如果您有多个,存储它们的索引和图像列表使它们易于访问。

Most scripts will have a few images in play and animate the change, giving it a slide show or carousel effect.大多数脚本将播放一些图像并为更改设置动画,使其具有幻灯片或轮播效果。 Since you're just showing one, it's easy enough to just change the source.由于您只是展示一个,因此只需更改源就很容易了。

Try to simply your code add Document.getElementById to the body or bodyonload then run a function and add an image using the tag as thats how you add images on javascript standard尝试简单地将您的代码添加 Document.getElementById 到 body 或 bodyonload 然后运行 ​​function 并使用标签添加图像,这就是您在 javascript 标准上添加图像的方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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