代码之家  ›  专栏  ›  技术社区  ›  Summer

jquery:在绑定函数中执行代码片段onload

  •  0
  • Summer  · 技术社区  · 15 年前

    下面是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);
      });
    });
    
    1 回复  |  直到 15 年前
        1
  •  2
  •   Nick Craver    15 年前

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

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