[英]JavaScript Objects: Property Set but Returns undefined When Accessed
Greetings, 问候,
I'm working with a JavaScript object that is defined like so: 我正在使用这样定义的JavaScript对象:
var ytVideoData = new Object();
I then assign a value to it inside of a jQuery .ajax(): 然后,我在jQuery .ajax()中为其分配一个值:
$.ajax({
type: "GET",
url: "xmlproxy.php?url="+ytId+"&mode=native",
success: function(data) {
ytVideoData.thumbnail = $(data).find("media\\:thumbnail[yt\\:name='default']").attr("url"); // default thumbnail image
}
});
In another function, I want to access the thumbnail property I just set. 在另一个功能中,我要访问刚刚设置的缩略图属性。 However, when I do:
但是,当我这样做时:
function addPlaylistItem(tumblrUser, videoData) {
console.log(videoData.thumbnail);
}
All I get in the console is "undefined". 我在控制台中得到的只是“未定义”。 When I do:
当我做:
console.log(videoData);
I get the entire object logged to the console and can see the thumbnail property properly set inside of the object like so: 我将整个对象记录到控制台,可以看到在对象内部正确设置的thumbnail属性,如下所示:
http://mp3.deceast.com/js-objectissue.jpg http://mp3.deceast.com/js-objectissue.jpg
After trying several different methods I just can't seem to get it work. 在尝试了几种不同的方法之后,我似乎无法正常工作。 How do I access this object property?
如何访问该对象属性?
A callback via ajax is asychronous. 通过ajax进行的回调是异步的。 WHich means you can't tell when it will run the success function.
这意味着您无法确定何时将运行成功功能。
The order that is probably happening is 可能发生的顺序是
$.ajax
addPlaylistItem // undefined
success // defined
Try calling the function in the success postback 尝试在成功回发中调用该函数
success: function(data) {
ytVideoData.thumbnail = $(data).find("media\\:thumbnail[yt\\:name='default']").attr("url"); // default thumbnail image
addPlaylistItem(getTumblrUser(), ytVideoData);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.