使用JSON文件动态更改图像内容?

时间:2017-12-04 19:37:47

标签: javascript jquery html json slideshow

基本上我想创建一个JS脚本(使用jQuery),它使用被点击的<div class="box">元素的id,在JSON文件中找到相应的“id”值,然后添加“image”url值到<div class="output-box">元素。我不确定执行此操作的最佳方法是使用<img>标记,还是使用jQuery代码更改CSS background-image属性(或完全不同的方式),理想情况下我是当用户点击每个盒子时,我想在图像之间淡入淡出。

我的HTML文件设置如下:

<div class="box" id="1"><h1>Box 1</h1></div>
<div class="box" id="2"><h1>Box 2</h1></div>
<div class="box" id="3"><h1>Box 3</h1></div>

<div class="output-box"></div>

一个单独的JSON文件:

{    
    "content" : [
        {
        "id"     : 1,
        "image"  : "img/test01.jpg"
        },        
        {
        "id"     : 2,
        "image"  : "img/test02.jpg"
        },        
        {
        "id"     : 3,
        "image"  : "img/test03.jpg"
        }        
    ]    
}

一个JS文件(使用jQuery),设置如下:

$.getJSON('content.json', function (data) {

    "use strict";

    var content = data.content;


    $('.box').click(function () {

        //Box <div> id is obtained on click
        //Object with corresponding 'id' value from JSON file is then found
        //Image url is then used to add the image to the '.output-box' <div>

    });

});

Desired Result.

无论添加了多少<div class="box">个元素,都需要轻松扩展和工作。

详细的答案将不胜感激,因为我仍然是JS和JSON的新手,并没有找到任何准确解释我想要实现的目标。

谢谢! :)

1 个答案:

答案 0 :(得分:2)

以下是一种方法:

// set a click handler on all .box elements
$('.box').click(function () {

  // return the first element, if it exists, of the content array that has a matching id to the clicked .box element's id
  var c = content.find(o => o.id == this.id);

  // make sure there was a match
  if (c) {
    // append an image with the appropriate .src property
    $('.output-box').append("<img src='" + c.image + "'>");
  }
});
相关问题