在contenteditable中添加新行时字数错误

Word count is wrong when adding new line in contenteditable

本文关键字:错误 新行时 添加 contenteditable      更新时间:2023-09-26

我计算contenteditable中的单词。我用空格分隔它。当您输入新行时,问题就出现了。在你添加空格之前,它不会计算你当前在新行上写的单词。

最重要的是,在下面的例子中,如果你把示例文本分成两行,当你这样做的时候,它会"吃掉"一个单词:

http://jsfiddle.net/MrbUK/

我猜这个问题的存在是因为HTML元素之间没有空格:

<div>some things</div><div>are cool</div>的字符串将是"somethingsare cool"

这是我的代码:

function wordCount() {
var content_text = $('#post_content').text(),
    char_count = content_text.length,
    word_count = 0;
    // if no characters, words = 0
    if (char_count != 0) 
      word_count = content_text.replace(/[^'w ]/g, "").split(/'s+/).length;
$('.word_count').html(word_count + " words &nbsp;&bull;&nbsp; " + char_count + " characters");
}

我试着替换一些HTML标签:

word_count = content_text.replace(/&nbsp;/g, " ").replace(/<div>/g, "<p>").replace(/<'/div>/g, "</p>").replace(/<'/p><p>/g, " ").split(/'s+/).length;

没有任何运气。我需要丢弃它是<p>还是<div>,一些浏览器在合并行时会添加&nbsp;

有什么想法吗?谢谢


编辑:感谢下面的杰弗逊的聪明方法,我成功地解决了这个问题。出于某种原因,我不得不在word_count上做-1来显示正确的字数:

function wordCount() {
  var content_div = $('#post_content'),
      content_text,
      char_count = content_div.text().length,
      word_count = 0;
  // if no characters, words = 0
  if (char_count != 0) 
    content_div.children().each(function(index, el) {
      content_text += $(el).text()+"'n";
    });
  // if there is content, splits the text at spaces (else displays 0 words)
  if (typeof content_text !== "undefined")
    word_count = content_text.split(/'s+/).length - 1;
  $('.word_count').html(word_count + " words &nbsp;&bull;&nbsp; " + char_count + " characters");
}

您可以使用这个:

$("#post_content").children().each(function(index, el){buffer += $(el).text()+"'n"})

通过这种方式,您可以迭代div中的所有元素,只获取文本,在它们之间放一个"''n"。

Jefferson的回答很好,它帮助我解决了同样的问题。我遇到的问题是contenteditablediv的内容没有完全封装在HTML标记中。

例如,我的div包含以下HTML代码:

This is my first line<div>This is my second line</div>

通过使用$.children(),它忽略了第一行,只返回5的字数。为了解决这个问题,我使用了$.contents()。修改后的代码如下:

$("#post_content").contents().each(function(index, el){buffer += $(el).text()+"'n"})

这返回了行计数10。

很抱歉把这作为一个答案,而不是对杰斐逊的答案的评论,但我的声誉太低,不允许我这么做。不过,我觉得指出以上几点是值得的。