javascript JQuery附加'[object,Object]'而不是图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7883058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery appending '[object, Object]' rather than image
提问by max_
I am using the $.getJSON
function of JQuery to download the urls of some images and I am trying to output them inside a div. I am trying to get the output to look like this:
我正在使用$.getJSON
JQuery的功能来下载一些图像的 url,并试图将它们输出到一个 div 中。我试图让输出看起来像这样:
<a href="the image url (shot.short_url)"><img src="the direct image url (shot.image_teaser_url)" /></a>
However, it is outputting this instead:
但是,它正在输出这个:
<div id="body-wrapper">
<a href="http://drbl.in/300896">[object Object]</a>
<a href="http://drbl.in/298080">[object Object]</a>
<a href="http://drbl.in/290395">[object Object]</a>
<a href="http://drbl.in/290324">[object Object]</a>
<a href="http://drbl.in/268595">[object Object]</a>
<a href="http://drbl.in/265197">[object Object]</a>
<a href="http://drbl.in/256368">[object Object]</a>
<a href="http://drbl.in/252519">[object Object]</a>
<a href="http://drbl.in/242235">[object Object]</a>
<a href="http://drbl.in/241676">[object Object]</a>
</div>
Please can you tell me where I am going wrong in the case out outputting the image?
请你告诉我在输出图像的情况下我哪里出错了?
This is my code:
这是我的代码:
function work() {
$('#body-wrapper').empty();
$.getJSON("http://dribbble.com/jakekrehel/shots.json?callback=?", function(data){
$.each(data.shots, function(i,shot){
var image = $('<img/>').attr('src', shot.image_teaser_url);
var title = '<a href=\"' + shot.short_url + '\">';
var string = title;
string = string + image;
string = string + '</a>';
$('#body-wrapper').append(string);
});
});
}
采纳答案by Phil
Try this within your .each()
callback
在你的.each()
回调中试试这个
// create image
var image = $('<img>').attr('src', shot.image_teaser_url);
// create anchor and append image
var anchor = $('<a>').attr('href', shot.short_url).append(image);
// append anchor to container
$('#body-wrapper').append(anchor);
回答by max_
image is a jQuery object and not a String - so appending it to a String will produce [object Object]
图像是一个 jQuery 对象而不是一个字符串 - 所以将它附加到一个字符串将产生 [object Object]
Ideally, change everything into an object - e.g.
理想情况下,将所有内容更改为对象 - 例如
$('#body-wrapper').append(
$("<a/>",{"href": shot.short_url}).append(
$("<img/>",{"src": shot.image_teaser_url}));
or cheat and do this string = string + image.html();
或作弊并执行此操作 string = string + image.html();
Either should work
要么应该工作
Note: I typed those without syntax checking and there's a LOT of brackets, did my best tho!
注意:我在没有语法检查的情况下输入了那些,并且有很多括号,我已经尽力了!