我需要创建一个按需加载的图片库,我从一个JSON开始,它以如下格式定义库中的所有图像:
var GALLERY_JSON = {
"size" : "200x200",
"images": [
{
"src" : "http://aws.netclime.net/Images/1.png",
"text" : "This is an image1",
"link" : "http://cnn.com"
},
{
"src" : "http://aws.netclime.net/Images/2.png",
"text" : "This is an image2",
"link" : "http://google.com"
},
…,
{
"src" : "http://aws.netclime.net/Images/3.png",
"text" : "This is an imageN",
"link" : "http://yahoo.com"
}
]
};
我试过了:
function getArticleImage() {
var image = new Image;
image.className = 'banner-img';
image.src = 'aws.netclime.net/Images/1.png';
image.setAttribute("height", "200px");
image.setAttribute("width", "200px");
image.onload = function() {
image.classList.remove();
};
return image;
}
我需要一个建议,这是用HTML格式显示带有文本和链接的图像的正确方法吗?
答案 0 :(得分:0)
您应该遍历数组,创建包含图像的链接元素并将其附加到DOM。以下是提供文档和示例的两个链接:
答案 1 :(得分:0)
var GALLERY_JSON = {
"size" : "200x200",
"images": [
{
"src" : "http://aws.netclime.net/Images/1.png",
"text" : "This is an image1",
"link" : "http://cnn.com"
},
{
"src" : "http://aws.netclime.net/Images/2.png",
"text" : "This is an image2",
"link" : "http://google.com"
},
{
"src" : "http://aws.netclime.net/Images/3.png",
"text" : "This is an imageN",
"link" : "http://yahoo.com"
}
]
};
function getArticleImage(data) {
var image = new Image;
image.className = 'banner-img';
image.src = data.src;
image.setAttribute("height", data.height);
image.setAttribute("width", data.width);
image.onload = function() {
image.classList.remove();
};
return image;
}
GALLERY_JSON.images.forEach(function(data){
data.width = GALLERY_JSON.size.match(/^[0-9]+/);
data.height = GALLERY_JSON.size.match(/[0-9]+$/);
document.body.appendChild( getArticleImage(data) );
})

答案 2 :(得分:0)
我建议使用模板。
恕我直言,它是一个功能更强大的解决方案,您可以轻松更改模板,将您的数据嵌入到您想要的任何第三方图库/旋转木马中,并且更加清晰。
示例强>
以下是HTML中嵌入模板的示例(您可以将其放在那里以便更好地进行组织)
它依赖于
hacky .match()部分是提取宽度和高度,如果您可以在GALLERY_JSON中将这两个值作为变量提供,则您不需要这样做。
var GALLERY_JSON = {
"size" : "200x200",
"images": [
{
"src" : "http://aws.netclime.net/Images/1.png",
"text" : "This is an image1",
"link" : "http://cnn.com"
},
{
"src" : "http://aws.netclime.net/Images/2.png",
"text" : "This is an image2",
"link" : "http://google.com"
},
{
"src" : "http://aws.netclime.net/Images/3.png",
"text" : "This is an imageN",
"link" : "http://yahoo.com"
}
]
};
var width = GALLERY_JSON.size.match(/^[0-9]+/);
var height = GALLERY_JSON.size.match(/[0-9]+$/);
GALLERY_JSON.width = width;
GALLERY_JSON.height = height;
var template = $('#template').html();
var gallery = Mustache.render(template, GALLERY_JSON);
$('#gallery').html(gallery);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.2.1/mustache.min.js"></script>
<div id="gallery"></div>
<script id="template" type="template/mustache">
<ul>
{{#images}}
<li>
<a href="{{link}}">
<img src="{{src}}" alt="{{text}}" height="{{height}}" width="{{width}}">
<p>{{text}}</p>
</a>
</li>
{{/images}}
</ul>
</script>
&#13;