我有这段代码
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");
});
返回正确的值
为什么会发生这种情况?如何让它发挥作用?
由于
答案 0 :(得分:1)
this.link
循环外部访问 each
。您只能从this
范围访问each
上下文。如果你想定义一些"模板"循环的ouside,您可以尝试:
var temp = "text %link% text";
$(data.query.results.item).each(function () {
alert(temp.replace('%link%', this.link));
});
答案 1 :(得分:1)
this
指的是执行它的上下文/范围,你的this
在每个之外执行,这就是未定义的原因 -
你可以尝试这样的事情 -
function getText(item){
var temp = "text " + item.link + " text";
}
$(data.query.results.item).each(function () {
alert(getText(this));
});
答案 2 :(得分:0)
因为this
总是引用当前对象。
var temp = "text " + this.link + " text";
这里this
未定义,这就是它显示该消息的原因。
答案 3 :(得分:0)
为什么不以这种方式使用每种方法!
$.each(data.query.results.item, function( index, value ) {
alert( "text " + value.link );
});