开发者

For Statement problem

开发者 https://www.devze.com 2023-04-01 01:53 出处:网络
I have a for statem开发者_如何学编程ent like function myspecialFunction(elem) { var currentItem = elem;

I have a for statem开发者_如何学编程ent 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


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.


Something like this using jQuery each loop

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号