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

2024-05-01

I have:简单的 html 文本块:

<p>
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...
</p>

I want:当用户点击它时,将单词包装到跨度中。

I.e.用户点击了manned词,比我应该得到的

<p>
The future of <span class="touched">manned</span> space exploration and development of space depends critically on the
creation of a ....

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

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

特别献给@DavidThomas: 例如,我获取选定的文本,但不知道如何将其包装到跨度中 http://jsfiddle.net/rk6fmmLg/.


我是你,我会把所有的话都用<span>预先标记并更改class单击时。这可能看起来像

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

然后我们可以有一个全局处理程序,它监听click events on <span> nodes

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

Example: http://jsfiddle.net/z54kehzp/ http://jsfiddle.net/z54kehzp/


我稍微修改了@Jonast92 解决方案,我也喜欢他的方法。对于大量数据来说,它甚至可能更好。唯一需要注意的是,您必须双击才能选择单词。

Example: http://jsfiddle.net/5D4d3/106/ http://jsfiddle.net/5D4d3/106/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在用户点击javascript时将单词包装到span中 的相关文章