这是我的jQuery字计数器代码的一部分。我的问题是:当页面加载时,以及在keyup、click、blur等事件上,我如何执行计算单词并显示结果的部分?我可以复制和粘贴,但这似乎太草率了。或者我可以将重复的比特放入另一个函数中,但是这样我的$(this)变量就不再起作用了。该怎么办呢?
$(".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);
});
});发布于 2010-04-08 03:13:21
在这一部分,只需在绑定后触发一次,如下所示:
$(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事件,也就是您刚刚绑定的事件,因此当此代码运行时,它也会触发您刚刚绑定的处理程序立即运行一次。
https://stackoverflow.com/questions/2594948
复制相似问题