侦测 和空间与JavaScript [英] Detect   and space with JavaScript
问题描述
我正在尝试读取contentEditable
div的内容并提取当前活动的单词. IE.刚输入的单词或已修改的单词.
I'm trying to read the content of a contentEditable
div and extract the currently active word. ie. the word which was just entered or one which was modified.
我最初的方法是:
- 将字符串作为
innerHTML
- 使用函数获取光标位置(现在我可以找到被修改的单词)
- 向后读取,直到找到一个空格(通过字符比较来查找字符)
- 从找到的空间中提取单词.
- get string as
innerHTML
- get cursor position using a function (now I can find the word that was modified)
- read backwards till a space is found (character by character comparison)
- extract the word from the point of space found.
但是问题是浏览器有时将空格转换为 
,有时却不(如果只有一个空格,这没有问题).然后,我决定使用第二个循环读取5个字符(如果找到了a ;
)并对此进行检查.但这似乎效率很低.那么有没有更好的方法可以做到这一点?
But the problem is that the browser sometimes converts the spaces to  
and sometimes doesn't (There is no problem if there is only one space). Then I decided to using a second loop to read in 5 chars if a ;
is found and check against that. But this is seems very inefficient. So is there a better way to do this?
推荐答案
我找到了一种解决方法.以前,我是使用innerHTML来获取内容的.
现在,我正在使用targ.firstChild.nodeValue
,其中targ是需要其内容的元素.然后使用 str.charCodeAt(i)==32 || str.charCodeAt(i)==160
进行检查.
I found a workaround. Previously, I was using innerHTML to get the contents.
Now, I'm using targ.firstChild.nodeValue
where targ is the element whose content is needed.Then checking with str.charCodeAt(i)==32 || str.charCodeAt(i)==160
.
这很好.
这篇关于侦测 和空间与JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!