使用 JSON 文件动态更改图像内容?
Dynamically change Image content using JSON file?
基本上我想创建一个 JS 脚本(使用 jQuery),它使用点击的 <div class="box">
元素的 id,在 [=44= 中找到相应的 "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>
});
});
无论添加多少 <div class="box">
元素,这都需要易于扩展和工作。
将不胜感激详细的答案,因为我对 JS 和 JSON 还很陌生,还没有找到任何能准确解释我正在努力实现的目标。
谢谢! :)
这是一种方法:
// 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 + "'>");
}
});
基本上我想创建一个 JS 脚本(使用 jQuery),它使用点击的 <div class="box">
元素的 id,在 [=44= 中找到相应的 "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>
});
});
无论添加多少 <div class="box">
元素,这都需要易于扩展和工作。
将不胜感激详细的答案,因为我对 JS 和 JSON 还很陌生,还没有找到任何能准确解释我正在努力实现的目标。
谢谢! :)
这是一种方法:
// 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 + "'>");
}
});