如何在用户单击javascript时将文字包装成跨度 [英] How to wrap word into span on user click in javascript

查看:84
本文介绍了如何在用户单击javascript时将文字包装成跨度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$

< p> 


载人太空探索和太空发展的未来主要取决于
创建的航天运输显着更精通的推进架构。
调查核动力在火箭中的适用性的一个非常有说服力的理由是,与化学燃烧能量相比,核燃料的能源密度增加
...
< / p>

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



ie 用户点击了 字样,比我应该得到的更多。

 < p> 
< span class =touching>有人驾驶< / span>的未来太空探索和太空的发展很大程度上取决于
的创造....

问题:如何做到这一点?有没有更有效率的方法可以在装载阶段将所有文字都包含进来?



PS 我对 window.getSelection(),因为我想暗示某些特定的被感动单词的样式,并且还保留了被感动的单词的集合。

特殊对于@DavidThomas: 示例,我可以获取选定的文本,但不知道如何将其包裹到跨度

解决方案

我是你,我会用< span> 标签,只需在点击时更改 class 即可。这可能看起来像

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

然后我们可以有一个全局处理函数,它监听 click events < span> 节点

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

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






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



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


I have: Simple block of html text:

<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: wrap word into span when user click on it.

I.e. User clicked at manned word, than I should get

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

Question: How to do that? Is there way more efficient that just wrap all words into span at loading stage?

P.S. I'm not interested in window.getSelection() because I want to imply some specific styling for touched words and also keep collection of touched words

Special for @DavidThomas: example where I get selected text, but do not know how to wrap it into span.

解决方案

I were you, I'd wrap all words with <span> tags beforehand and just change the class on click. This might look like

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

and then we could have a global handler, which listens for click events on <span> nodes

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

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


I modified @Jonast92 solution slightly, I like his approach also. It might even be better for huge data amounts. Only caveat there, you have to live with a doubleclick to select a word.

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

这篇关于如何在用户单击javascript时将文字包装成跨度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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