John B
John B

Reputation: 5495

For Statement problem

I have a for statement like

function myspecialFunction(elem) {

var currentItem = elem;
var currentImg = elem.find('img');

jQuery(currentImg).append('some text');
...

The problem seems to be that when elem has >1 of the same image item - it overwrites the data of the previous ? That is, when the same currentImg is returned - the statement overwrites the data of the previous ?

How can I ensure that same currentImg values are preserved ? i.e. I was hoping to use like $(this) but it doesn't appear to work ? My html looks like

Upvotes: 0

Views: 84

Answers (3)

Russ Cam
Russ Cam

Reputation: 125488

You could rewrite the above as

jQuery('.class').each(function() {
    myspecialFunction(jQuery(this));
});

function myspecialFunction(elem) {  
    var currentItem = elem;
    var currentImg = elem.find('img');

//....
}

this is more idiomatic and $(selector).each() introduces a closure to ensure that the correct value is captured in each loop iteration.

To do something similar with a plain for loop would be

var myClass = jQuery('.class');

for (var i = 0, len = myClass.length; i < len; i++) {
    (function () {
        myspecialFunction(jQuery(myClass[i]));
    })();
}

function myspecialFunction(elem) {

    var currentItem = elem;
    var currentImg = elem.find('img');
    // ...
}

Depending on your target browsers, being more specific than just a CSS class may help out too i.e. if all of the elements that you are selecting are all of the same tag name, then use the tag name in the selector.

Upvotes: 1

Neil N
Neil N

Reputation: 25258

currentImg is local to the function it is in... not only will it be overwritten on each call, it won't even exist outside of that function.

Do you want to create a list of values that elem.find('img') returns? If so then I think you are going about it wrong. You need to scope a list variable outside of the function.

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69905

Something like this using jQuery each loop

jQuery('.class').each(function(){
    myspecialFunction($(this));
});

Upvotes: 0

Related Questions