簡體   English   中英

.each()函數中的jQuery變量

[英]jQuery variable inside .each() function

我有這段代碼

var temp = "text " + this.link + " text";

$(data.query.results.item).each(function () {
    alert(temp);
});

當收到警報時,它會返回“文本未定義文本”

但如果我這樣做

$(data.query.results.item).each(function () {
    alert("text " + this.link + " text");
});

它返回正確的值

為什么會發生這種情況,我怎樣才能讓它發揮作用?

謝謝

無法從each循環的外部訪問this.link 您只能從each范圍訪問this上下文。 如果你想定義循環的一些“模板”,你可以試試:

var temp = "text %link% text";

$(data.query.results.item).each(function () {
    alert(temp.replace('%link%', this.link));
});

this是指執行它的上下文/范圍,你的每個都在外面執行, this就是它未定義的原因 -

你可以試試這樣的東西 -

function getText(item){
  var temp = "text " + item.link + " text";
}

$(data.query.results.item).each(function () {
    alert(getText(this));
});

因為this總是指當前對象。

var temp = "text " + this.link + " text";

this是未定義的,這就是它顯示該消息的原因。

為什么不以這種方式使用每種方法!

$.each(data.query.results.item, function( index, value ) {
    alert( "text " + value.link );
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM