thetester
thetester

Reputation: 13

jQuery troubles with each() and custom function

    $(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>

Upvotes: 1

Views: 1116

Answers (3)

just somebody
just somebody

Reputation: 19247

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

Upvotes: 0

mck89
mck89

Reputation: 19231

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");
}

Upvotes: 5

Koobz
Koobz

Reputation: 6938

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");
        });
    });

Upvotes: 2

Related Questions