How to display image and its corresponding text
I am getting data as json through jquery and after parsing it I am getting some images and corresponding to these images some text. My problem is I want to display on my web page like this. "some image" : corresponding text.
How can I do this.
The problem is here:
$.each(result.response.docs, function(i,item){
src1=item.image;
html+="<p><br>"+"<img src="+src1+ " />";
html += " UID_PK: ="+ item.UID_PK;
html += "<br>Name: ="+ item.name;
html += "<br>Description: ="+ item.description;
html += "<br>Price: ="+ item.price;
// ("#result").html(html);
// alt1="No Image"
//image+="<br>IMAGE: "+"<img src="+src1+ " alt="+alt1+ " />";
//image+="开发者_JS百科<br>"+"<img src="+src1+ " />";
})
$("#result").html(html);
where result is a . I wanted to ask should I make separate div for both image and text. And if I do this then I'll have to call $("#result").html(html); ("#image").html(image);
in side the loop. And what if I do not have images for some text, then I want to make that space blank.
var imgAndText = '';
if(jsonObject.imgSrc != null || jsonObject.imgSrc != "") {
imgAndText += "<img src='"+jsonObject.imgSrc+"' alt='"+jsonObject.imgText+"' />";
} else {
imgAndText += "<div class='image_placeholder'></div>";
}
imgAndText += "<br/>";
imgAndText += "<p>"+jsonObject.imgText+"</p>";
document.write(imgAndText);
I think what you are trying to do is display your JSON image and text from javascript! Here's a crude solution:
var imgAndText = "<img src='"+jsonObject.imgSrc+"' />";
imgAndText += "<br/>";
imgAndText += "<p>"+jsonObject.imgText+"</p>";
document.write(imgAndText);
This constructs the html and displays it on the page!
EDIT
if there is no image:
var imagAndText;
if(jsonObject.imgSrc != null && jsonObject.imgSrc != "") {
imgAndText = "<img src='"+jsonObject.imgSrc+"' />";
} else {
imgAndText = "<img src='defaultImg.jpg' />";
}
imgAndText += "<br/>";
imgAndText += "<p>"+jsonObject.imgText+"</p>";
document.write(imgAndText);
This should check to see if there is an imgSrc in the jsonObject...if there is, use it else use a predefined image which could be blank or anything you want.
EDIT 2
Just clarifying from @Anze below...
change the else closure to :
else {
imgAndText = "<div class="image_placeholder"></div>";
}
in your css:
.image_placeholder {
width:150px; /*your default width*/
height:150px; /*your default height*/
}
精彩评论