【问题标题】:Word count is wrong when adding new line in contenteditable在 contenteditable 中添加新行时字数错误
【发布时间】:2013-02-07 04:30:50
【问题描述】:

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

最重要的是,在下面的示例中,如果您将示例文本分成两行,那么当您这样做时,它会“吃掉”一个单词:

http://jsfiddle.net/MrbUK/

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

<div>some things</div><div>are cool</div> 它的字符串是“some thingsare 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  •  " + 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;

没有任何运气。无论是&lt;p&gt; 还是&lt;div&gt;,我都需要丢弃,有些浏览器在合并行时会添加&amp;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");
}

【问题讨论】:

  • sashok - 很好的问题。很详细。感谢您使用 jsfiddle
  • 计数关闭,甚至没有按回车键:console.log(content_text.replace(/[^\w ]/g, "").split(/\s+/)); 第一个索引是一个空字符串。

标签: javascript jquery html counter contenteditable


【解决方案1】:

你可以用这个:

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

这样,您可以遍历 div 中的所有元素并仅获取文本,在它们之间放置一个“\n”。

【讨论】:

  • buffer 是一个字符串,我没有把它放在代码中,但我想你明白它是如何工作的
  • 谢谢,聪明的解决方案。我用你的方法用我的答案编辑了我的问题。
【解决方案2】:

Jefferson 的回答很棒,它帮助我解决了同样的问题。 我遇到的问题是我的contenteditable div 的内容没有完全包裹在 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 行数。

很抱歉将此添加为答案,而不是作为对杰斐逊答案的评论,但是我的声誉太低,不允许我这样做。不过,我觉得值得指出以上内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多