jQuery: execute a code snippet onload AND in a bound function
Here's part of my code for a jQuery word counter. My question is: how do I execute the part that counts the words and displays the result when the page -loads- as well as on keyup, click, blur etc. events? I could copy-and-paste, but that seems so sloppy. Or I could pull the repeated bit into another function, but then my $(this) variable won't work anymore. What to do?
$(".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 numWo开发者_如何学JAVArds = jQuery.trim($(this).val()).replace(/\s+/g," ").split(' ').length;
// Display the result
$(this).next('.word-count').children('strong').text(numWords);
});
});
On this part, just trigger it once after binding, like this:
$(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();
This triggers the keyup
event one time, the one you just bound, so when this code runs, it'll trigger the handler you just bound to run immediately once as well.
精彩评论