$(function(){
$(".test").each(function(){
test();
});
});
function test(){
$(this).css("border","1px solid red").append(" checked");
}
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?我错过了什么?这是我的测试html:
<p>test</p>
<p>test</p>
<p class="test">test</p>
<p>test</p>
Run Code Online (Sandbox Code Playgroud)
$(this)不能以这种方式使用,因为您没有指定test()函数的上下文:
$(".test").each(function(){
test($(this));
});
function test(el){
el.css("border","1px solid red").append(" checked");
}
Run Code Online (Sandbox Code Playgroud)
要么
$(".test").each(function(){
test.call(this);
});
function test(){
$(this).css("border","1px solid red").append(" checked");
}
Run Code Online (Sandbox Code Playgroud)