2010-04-07 36 views
0

這裏是我的代碼爲jQuery字計數器的一部分。我的問題是:如何執行計算單詞的部分,並在頁面加載時以及在鍵入,單擊,模糊等事件時顯示結果?我可以複製並粘貼,但看起來很sl。。或者我可以將重複的位拖放到另一個函數中,但是我的$(this)變量不再工作。該怎麼辦?jQuery:執行代碼片段onload和綁定函數

$(".count").each(function() { 

    // Set up max words 
    maxWords = 200; 

    // Set up div to display word count after my textarea 
    $(this).after('<div class="word-count"><strong>0</strong> Words ('+maxWords+' Maximum)</div>'); 

    // Bind function to count the words 
    $(this).bind('keyup click blur focus change paste', function() { 

    // Count the words 
    var numWords = jQuery.trim($(this).val()).replace(/\s+/g," ").split(' ').length; 

    // Display the result 
    $(this).next('.word-count').children('strong').text(numWords); 
    }); 
}); 
+0

只是將它包裝在'$(function(){/// your call})中;' – vittore 2010-04-07 18:41:27

回答

2

在這一部分,只是結合後觸發一次,像這樣:

$(this).bind('keyup click blur focus change paste', function() { 
    var numWords = jQuery.trim($(this).val()).replace(/\s+/g," ").split(' ').length; 
    $(this).next('.word-count').children('strong').text(numWords); 
}).keyup(); 

這觸發了keyup事件一次,你只要綁定的一個,所以,當這代碼運行,這是會立即觸發你剛剛綁定的處理程序。

+0

完美工作,謝謝。 – Summer 2010-04-07 19:20:51