$(this)的值随确认而变化

Tom*_*Tom 4 jquery

我想知道为什么$(this)不按照我期望的方式工作?在下面的代码中,单击"删除图像"时没有任何反应.如果您注释掉确认语​​句,则单击"删除图像"时背景将变为绿色.你知道为什么吗?$(this)由于确认声明,它似乎指向其他东西.提前致谢!

<a href="#" class='thumbnail the-one delete-file'><i class="icon-remove"></i>Remove Image</a>

$('.the-one').click(function(){
    if(confirm("What do you say?")) { return true;} else {return false;}
    $(this).css("background", "green");

});
Run Code Online (Sandbox Code Playgroud)

xda*_*azz 5

因为你有return它.之后的一切return都不会运行.


din*_*jas 5

您在设置css之前返回,因此该行未被执行.尝试:

$('.the-one').click(function(){
    if (confirm("What do you say?")) { 
        $(this).css("background", "green");
        return true;
    } else {
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)