2010-04-07 31 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