开发者

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>


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


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


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜