jQuery:在加载和绑定函数中执行代码段

jQuery:在加载和绑定函数中执行代码段,jquery,Jquery,这是我的jQuery单词计数器代码的一部分。我的问题是:当页面加载时,以及在键控、单击、模糊等事件中,如何执行计算单词并显示结果的部分?我可以复制粘贴,但这看起来太草率了。或者我可以将重复的位拉到另一个函数中,但是我的$(this)变量将不再工作。怎么办 $(".count").each(function() { // Set up max words maxWords = 200; // Set up div to display word count after my tex

这是我的jQuery单词计数器代码的一部分。我的问题是:当页面加载时,以及在键控、单击、模糊等事件中,如何执行计算单词并显示结果的部分?我可以复制粘贴,但这看起来太草率了。或者我可以将重复的位拉到另一个函数中,但是我的$(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);
  });
});
$(“.count”)。每个(函数(){
//设置最大字数
maxWords=200;
//设置div以在我的文本区域后显示字数
$(此)。在(“0Words(“+maxWords+”Maximum)”之后;
//Bind函数来计算单词数
$(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);
});
});

在这部分,绑定后只需触发一次,如下所示:

$(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
事件一次,即您刚才绑定的事件,因此当此代码运行时,它也会触发您刚才绑定的处理程序立即运行一次