2013-03-01 57 views
0

想有一个词柜台旁边的网站字计数器的JavaScript函数调用

上输入文本框得到它的工作,显示计数,当用户点击或修改的文字,但我想加载直线距离时页面完成加载。

$(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'); 
} 
}); 

非常感谢。

+0

什么不起作用/ – gdoron 2013-03-01 06:28:05

+0

我们需要更多信息来回答您的问题。它抛出一个错误? – yourdeveloperfriend 2013-03-01 06:30:51

回答

2

试试这个

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

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

演示:​​

问题是页面加载过程中您的通话displayText()。在displayText中,您曾使用$(this)访问输入字段,该字段用作事件处理程序。但是当你直接拨打displayTextthis会指向窗口对象。

+0

非常感谢您的帮助和解释! – user648198 2013-03-01 12:21:08

0

尝试.on()与多个事件。

$("#product_name").on({ 
    change: function() { 
     // Handle change event 
    }, 
    keyup: function() { 
     // Handle keyup 
    } 
}); 

和“当页面加载完成时”。使用$(window).load(function() { });