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

3 Answers 3

5

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");
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

If we are going to just need the function once, then the anonymous function keeps all the logic in one place.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.