$(this) 未被识别

$(this) is not being recognized

我正在使用以下调用一个函数,然后在一个或多个具有 class "textprop" 的文本框中设置文本格式。如果我给函数变量一个文本框的特定 id(即 $(#myid).val();)它可以工作,但我无法让它识别 "this"。我做错了什么?

$(".textprop").keyup(function(){
    textProp();
});

function textProp() {
    var str = $('this').find('.textprop').val();
    str.val(str.replace(/\b\w+/g,function(s){return s.charAt(0).toUpperCase() + s.substr(1).toLowerCase();}));
}

更新

我认为这行得通,但我一定是无意中输入了大写字母。以下是更新后的代码,但仍然不起作用。

$(".textprop").keyup(function(){
    var str = $(this).find('.textprop').val();
    str.val(str.replace(/\b\w+/g,function(s){return s.charAt(0).toUpperCase() + s.substr(1).toLowerCase();}));
});

最终解决方案

在 Charlietfl 的帮助下,这是最终的解决方案...

$(".textprop").keyup(function(){
    var str = $(this).val();
    $(this).val(str.replace(/\b\w+/g,function(s){return s.charAt(0).toUpperCase() + s.substr(1).toLowerCase();}));
});

为了在函数内部维护 this 的上下文,您需要将函数作为引用传递,而不是将其包装为匿名函数

$(".textprop").keyup(textProp);

另一种方法是使用 javascript bind() 将上下文传递给函数

注意$('this')应该是$(this)