在contenteditable中添加新行时字数错误
Word count is wrong when adding new line in contenteditable
我计算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 • " + char_count + " characters");
}
我试着替换一些HTML标签:
word_count = content_text.replace(/ /g, " ").replace(/<div>/g, "<p>").replace(/<'/div>/g, "</p>").replace(/<'/p><p>/g, " ").split(/'s+/).length;
没有任何运气。我需要丢弃它是<p>
还是<div>
,一些浏览器在合并行时会添加
。
有什么想法吗?谢谢
编辑:感谢下面的杰弗逊的聪明方法,我成功地解决了这个问题。出于某种原因,我不得不在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 • " + char_count + " characters");
}
您可以使用这个:
$("#post_content").children().each(function(index, el){buffer += $(el).text()+"'n"})
通过这种方式,您可以迭代div
中的所有元素,只获取文本,在它们之间放一个"''n"。
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。
很抱歉把这作为一个答案,而不是对杰斐逊的答案的评论,但我的声誉太低,不允许我这么做。不过,我觉得指出以上几点是值得的。
相关文章:
- 当在ng视图中加载新路由时,Tabbing(tabindex)针对错误的元素
- NodeJS Fork-每次子流程发送新行时都进行React
- 在使用 javascript 动态添加行时,我正在增加索引值,但出现错误
- 当数组达到大于 x 的数字时,继续新行
- 如何在javascript中每次添加新行时都增加ordre值
- 类型错误:无法读取属性'行'使用javascript删除行时为null
- 在Spring.message属性中添加新行时出错
- 当上一行/当前行被填充时,将新行添加到HTML表中
- 当单击在表中创建新行时,它只会短暂出现
- 当添加新行时,输入名称将增加1
- 添加新行时的日期增量
- 当添加新行时,总持续时间值应该会更改,但不会更改;t
- 在向表中添加新行时进行拦截
- 添加新行时,jQuery代码不起作用
- 在jQuery中添加新行时,禁用其他选择框的选择选项
- Jquery在创建新行时不向最后一行添加索引
- 当值为初始值时,在新行末尾放置错误消息
- 在dojo.gridX中添加新行时如何聚焦第二个Cell
- 在contenteditable中添加新行时字数错误
- 在添加具有模态形式的新行时,使用jqGrid添加附加参数以发布数据