如何在用户点击javascript中将单词包装成span

我有:简单的html文本块:

The future of manned space exploration and development of space depends critically on the creation of a dramatically more proficient propulsion architecture for in-space transportation. A very persuasive reason for investigating the applicability of nuclear power in rockets is the vast energy density gain of nuclear fuel when compared to chemical combustion energy...

我想:当用户点击它时将单词换成span。

用户点击了载人字,而不是我应该得到的

 

The future of manned space exploration and development of space depends critically on the creation of a ....

问题:怎么做? 是否有更高效的方法只是在加载阶段将所有单词包装到span中?

PS我对window.getSelection()不感兴趣,因为我想为触摸的单词暗示一些特定的样式,并且还保留触摸单词的集合

@DavidThomas的特别之处: 我获得选定文本的例子,但不知道如何将其包装成span 。

我是你,我事先用标签包装所有单词,只需点击即可更改class 。 这可能看起来像

 $( 'p' ).html(function( _, html ) { return html.split( /\s+/ ).reduce(function( c, n ) { return c + '' + n + ' ' }); }); 

然后我们可以有一个全局处理程序,它侦听节点上的click events

 $( document.body ).on('click', 'span', function( event ) { $( event.target ).addClass( 'touch' ); }); 

示例 : http : //jsfiddle.net/z54kehzp/


我略微修改了@ Jonast92解决方案,我也喜欢他的方法。 对于巨大的数据量,它甚至可能更好。 只有在那里警告,你必须用双击来选择一个单词。

示例 : http : //jsfiddle.net/5D4d3/106/

我修改了之前的答案 , 几乎可以获得您正在寻找的内容,如本演示中所示 。

它找到当前单击的单词并在字符串周围包含该特定类的跨度,并用新内容替换段落的内容,该新内容先前单击的单词将替换为新包装的字符串。

它有点受限,因为如果你点击另一个单词的子字符串,让我们说’是’,那么它将尝试替换段落中该字符串的第一个实例。

你可以用它来实现你想要的东西,但最重要的是环顾四周。

修改后的代码

 $(document).ready(function() { var p = $('p'); p.css({ cursor: 'pointer' }); p.dblclick(function(e) { var org = p.html(); var range = window.getSelection() || document.getSelection() || document.selection.createRange(); var word = $.trim(range.toString()); if(word != '') { var newWord = ""+word+""; var replaced = org.replace(word, newWord); $('p').html(replaced); } range.collapse(); e.stopPropagation(); }); }); 

然后,@ jAndy的回答看起来很有希望。

你的答案激发了我对下一个解决方案 :

 $(document).ready(function() { var p = $('p'); p.css({ cursor: 'pointer' }); p.dblclick(function(e) { debugger; var html = p.html(); var range = window.getSelection() || document.getSelection() || document.selection.createRange(); var startPos = range.focusOffset; //Prob: isn't precise +- few symbols var selectedWord = $.trim(range.toString()); var newHtml = html.substring(0, startPos) + '' + selectedWord + '' + html.substring(startPos + selectedWord.length); p.html(newHtml); range.collapse(p); e.stopPropagation(); }); }); 

我们没有在每个单词中包装。 相反,我们只在点击时包装单词。