题
$(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>
解决方案
在$(这)不能以这种方式使用的,因为你不指定测试()函数的背景:
$(".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");
}
其他提示
您的测试函数中,this
不绑定到你认为它一定是一样的。使用调试器像萤火虫,看看你实际上与合作。
在惯用的方法来做到这将是简单地包括封闭的测试内的主体(函数(){...})。
其他的解决方案,你可以使用应用功能( 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");
});
});
任一test.call(this);
或test(this);
和改变的定义。
不隶属于 StackOverflow