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

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

为什么这不起作用?我错过了什么?这是我的测试html:

    <p>test</p>
    <p>test</p>
    <p class="test">test</p>
    <p>test</p>
4

3 回答 3

5

$(this) 不能以这种方式使用,因为您没有指定 test() 函数的上下文:

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

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

或者

$(".test").each(function(){
      test.call(this);
});
function test(){
   $(this).css("border","1px solid red").append(" checked");
}
于 2010-02-01T11:41:05.090 回答
2

在你的测试函数内部,this它并没有绑定到你认为绑定的相同的东西。使用像 firebug 这样的调试器来查看您实际使用的是什么。

这样做的惯用方法是简单地将测试主体包含在闭包中(function() { ... })。

其他解决方案,您可以使用 apply 函数(https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Function/Apply)来控制this引用的内容。在这种情况下,这是矫枉过正,实际上,我发现最好避免它。

$(function(){
        $(".test").each(function(){
            $(this).css("border","1px solid red").append(" checked");
        });
    });
于 2010-02-01T11:40:38.007 回答
0

要么 要么test.call(this);test(this);更改定义。

于 2010-02-01T11:44:54.567 回答