希望网站上的输入文本框旁边有一个单词计数器

当用户单击或修改文本时,它可以正常显示计数,但是我想在页面加载完成后立即加载。

$(document).ready(function() {

  $("#product_name").change(displayText).keyup(displayText);

function displayText(){
      $("em#counter").text($(this).val().length +' chars');
}
});


所以我尝试了下面的代码,但无法正常工作,也不知道为什么。

$(document).ready(function() {

    if($("#product_name").length){
           displayText();
    }
  $("#product_name").change(displayText).keyup(displayText);

function displayText(){
      $("em#counter").text($(this).val().length +' chars');
}
});


非常感谢。

最佳答案

尝试这个

if($("#product_name").length){
           displayText();
}
$("#product_name").change(displayText).keyup(displayText);

function displayText(){
      $("em#counter").text($("#product_name").val().length +' chars');
}


演示:Fiddle

问题是页面加载期间的displayText()调用。在displayText中,您曾使用$(this)访问作为事件处理程序使用的输入字段。但是,当您直接调用displayText时,this将指向窗口对象。

10-06 00:28