views:

54

answers:

4
    $(function(){
        $(".test").each(function(){
            test();
        });
    });

     function test(){
        $(this).css("border","1px solid red").append(" checked");
    }

why is this not working? what am I missing? this is my test html:

    <p>test</p>
    <p>test</p>
    <p class="test">test</p>
    <p>test</p>
A: 

you are not holding a reference to this

$(".test").each(function(){
    $(this).css("border","1px solid red").append(" checked");
});

see docu for more information

Andreas Niedermair
Thanks for your fast answer dittodhole - but I need to call a function in this each-loop.How should it look like, when I want to call my test() function in this each-loop? why is $(this) not referencing to my called selector in the loop?
thetester
because: you are not in the same **scope** as your `each`-call. this is more a **fundamental** question than a jquery-specific one!
Andreas Niedermair
+1  A: 

Inside of your test function, this is not bound to the same thing you think it's bound to. Use a debugger like firebug to see what you're actually working with.

The idiomatic way to do this would be to simply include the body of test inside of the closure (function() { ... }).

Other solutions, you can use the apply function (https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Function/Apply) to control what this refers to. In this case, it's overkill, and actually, I find that it's best to avoid it in general.

$(function(){
        $(".test").each(function(){
            $(this).css("border","1px solid red").append(" checked");
        });
    });
Koobz
If we are going to just need the function once, then the anonymous function keeps all the logic in one place.
DavidA
+3  A: 

The $(this) cannot be used in that way, because you don't specify the context of the test() function:

$(".test").each(function(){
        test($(this));
});

function test(el){
     el.css("border","1px solid red").append(" checked");
}

or

$(".test").each(function(){
      test.call(this);
});
function test(){
   $(this).css("border","1px solid red").append(" checked");
}
mck89
Great! Thank you very much!That's what I needed!
thetester
A: 

either test.call(this); or test(this); and change the definition.

just somebody