![](/img/trans.png)
[英]How do i access the objects inside the array returned by a javascript function
[英]How can i access the objects variable inside an objects function (javascript)?
(function () {
var id="test";
$.ajax({
context: this,
url : "http://weather.yahooapis.com/forecastrss",
success : function(data){
this.id = "was test";
}
});
console.log(id);
})();
前面的問題還不夠清楚,所以請聽一下問題的實質是什么。 當我做console.log(id)
它不顯示更改后的值。 我想得到的是id
的更改后的值。 我如何才能做到這一點,我已經嘗試了評論中的所有解決方案以及給出的答案,但沒有一個對我有用?
jsFiddle將受到高度贊賞。
在getTodayCats中 :
var self = this;
然后,當需要訪問id時 ,應該這樣獲取它:
self.ids
自我的使用,這種模式在這種情況下,因為你需要訪問一個異步回調處理程序(阿賈克斯成功)的這種屬性進行。 異步回調的處理程序在沒有原始this對象的情況下被調用,因此該方法用於利用函數的閉包傳遞原始對象。
如果使用jQuery的ajax方法,您還可以使用context選項傳入this對象, 該對象將用作其回調處理程序。 是否使用它取決於您。 我個人不喜歡這樣做,因為這不是其他異步處理程序的選擇,例如在超時和間隔的情況下,並且我希望保持一致。
$.ajax({
url: "http://localhost/woodenspoon/getTodaysCats.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
responseType: "json",
context: this,
success: function (data) {
this.ids = "ok";
}
});
通過這種方式訪問“ ID”
getTodaysCats: function () {
var args = Array.prototype.slice.call( WinJS.UI.Pages.define.arguments);
var ids = args[1].ids;
$.ajax({
...
, success: function (data) {
var arr = new Array(1,2,3,4,5);
foreach(var num in arr)
ids += "ok";
}
});
return ids;
}
嘗試使用這樣的東西...
${variable}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.