这是一个非常简单的问题。 jQuery 是否有可能获取一个元素,并计算该元素(不是 textarea 或输入)中的单词和字符数并将其回显到 HTML 文档中?我能想到的唯一可行的代码是:

document.write("$('.content').text().length;")

我真的很不擅长 jQuery,但我正在努力学习它。如果有人可以提供脚本,那会很有帮助。

最佳答案

var txt = $('.content')[0].text()
  , charCount = txt.length
  , wordCount = txt.replace( /[^\w ]/g, "" ).split( /\s+/ ).length
  ;
$( '#somwhereInYourDocument' ).text( "The text had " + charCount + " characters and " + wordCount +" words" );

在拆分之前运行 replace 以去除标点符号,并使用正则表达式运行 split 以处理单词之间的新行、制表符和多个空格。

编辑 添加了 text( ... ) 位以写入节点,作为在另一个答案的评论中指定的 OP。

编辑 您仍然需要将它包装在一个函数中以使其在页面加载后工作
$( function(){
    var txt = $('.content')[0].text()
      , charCount = txt.length
      , wordCount = txt.replace( /[^\w ]/g, "" ).split( /\s+/ ).length
      ;
    $( '#somwhereInYourDocument' ).text( "The text had " + charCount + " characters and " + wordCount +" words" );
});

否则它会在页面上呈现任何内容之前运行

关于jQuery 字符和字数统计,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9864644/

10-12 12:50
查看更多