侦测 和空间与JavaScript [英] Detect   and space with JavaScript

查看:55
本文介绍了侦测 和空间与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.

我最初的方法是:

  1. 将字符串作为innerHTML
  2. 使用函数获取光标位置(现在我可以找到被修改的单词)
  3. 向后读取,直到找到一个空格(通过字符比较来查找字符)
  4. 从找到的空间中提取单词.
  1. get string as innerHTML
  2. get cursor position using a function (now I can find the word that was modified)
  3. read backwards till a space is found (character by character comparison)
  4. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆