Вопрос

Can someone find a problem in the code below

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

this works flawlessly,

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

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

    });
});

Any ideas?

Это было полезно?

Решение

this is not a local variable, so it isn't saved in the closure. You need to bind a local variable to it:

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

Другие советы

setTimeout does not invoke in the same scope. So this is not the same this as in your 2nd example.

...
var self = this;

setTimeout(function () {
  var txtVal = self.value;
  $('#content').css("font-size", txtVal + "%");
}, 3000);
...

Credit to Barmar who answered this on another thread.

"this" is not a local variable, so it isn't saved in the closure. You need to bind a local variable to it:

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

In code snippet, "this.value" returns "undefined" after 3 secs.

So, use selector, instead of this

$(document).ready(function() {
  $("#leftsettingswindow").on("keyup", "#fontsize2", function() {
   setTimeout(function() {
      var txtVal = $('#fontsize2').val();
      $('#content').css("font-size", txtVal + "%");
    }, 3000);
  });
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top