2013-03-01 55 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() { });