Reputation: 317
I have this piece of code
var temp = "text " + this.link + " text";
$(data.query.results.item).each(function () {
alert(temp);
});
When alerted it returns "text undefined text"
But if i do this
$(data.query.results.item).each(function () {
alert("text " + this.link + " text");
});
It returns the correct value
Why is this happening and how can i get it to work?
Thanks
Upvotes: 0
Views: 4623
Reputation: 9968
Why not use each method in this way!
$.each(data.query.results.item, function( index, value ) {
alert( "text " + value.link );
});
Upvotes: 0
Reputation: 44740
this
refer to the context/scope where it is executed, your this
is executed outside of each, that is why it is undefined -
You can try something like this -
function getText(item){
var temp = "text " + item.link + " text";
}
$(data.query.results.item).each(function () {
alert(getText(this));
});
Upvotes: 1
Reputation: 3820
Because this
always refers to the current object.
var temp = "text " + this.link + " text";
Here this
is undefined that's why it's showing that message.
Upvotes: 0
Reputation: 152216
this.link
is not accessible from the outside of the each
loop. You can get access this
context only from teh each
scope. If you want to define some "template" ouside of the loop, you can try with:
var temp = "text %link% text";
$(data.query.results.item).each(function () {
alert(temp.replace('%link%', this.link));
});
Upvotes: 1