回调函数中的setTimeout不起作用

San*_*dor 0 javascript jquery settimeout

有人可以在下面的代码中找到问题

$(document).ready(function () {
    $("#leftsettingswindow").on("keyup", "#fontsize2", function () {
        setTimeout(function () {
            var txtVal = this.value;
            $('#content').css("font-size", txtVal + "%");
        }, 3000);
    });
});
Run Code Online (Sandbox Code Playgroud)

这完美无缺,

$(document).ready(function () {
    $("#leftsettingswindow").on("keyup", "#fontsize2", function () {

            var txtVal = this.value;
            $('#content').css("font-size", txtVal + "%");

    });
});
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Bar*_*mar 5

this不是局部变量,因此它不会保存在闭包中.您需要将局部变量绑定到它:

$(document).ready(function () {
    $("#leftsettingswindow").on("keyup", "#fontsize2", function () {
        var savedThis = this;
        setTimeout(function () {
            var txtVal = savedThis.value;
            $('#content').css("font-size", txtVal + "%");
        }, 3000);
    });
});
Run Code Online (Sandbox Code Playgroud)