得到单词点击段落 [英] get word click in paragraphs

查看:87
本文介绍了得到单词点击段落的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML文档,其中包含大约30,000个单词。



我希望能够在用户点击任何单词时执行某些操作。为了简单/概念,我只想 alert()这个词。



例如,在段落中,如果我点击有它应该运行 alert(have)



<我正在使用jQuery。

解决方案

  var p = $('p' ); 

p
.html(函数(index,oldHtml){
返回oldHtml.replace(/ \b(\ w +?)\ b / g,'< span class =word> $ 1< / span>')
})
.click(function(event){alert(event.target.innerHTML)});

我拿了 Pablo Fernandez 的建议被考虑在内。



在jsFiddle上查看



更新




那么,这会有效吗(例如,它不会冻结慢用户的浏览器?)另外,你能详细说明event.target是如何工作的吗?


它可能会很慢地减慢30,000字的页面性能。我认为这是过度的,可能会受益于分页,但我不知道你的具体情况。



event.target property保存启动事件的元素 - 事件冒泡/传播到其父级,然后父级处理事件,因此您在单独的 span上没有30,000个事件元素。


I have an HTML document with about 30,000 words in it.

I'd like to be able to do something when a user clicks any word. For simplicity/concept right now, I'd just like to alert() that word.

For example, in the paragraph about, if I were to click on "have" it should run alert("have").

I'm using jQuery.

解决方案

var p = $('p');

p
 .html(function(index, oldHtml) {
    return oldHtml.replace(/\b(\w+?)\b/g, '<span class="word">$1</span>')
 })
 .click(function(event) { alert(event.target.innerHTML) });

I took Pablo Fernandez's suggestions into account.

See it on jsFiddle.

Update

So, will this be performant (e.g., it won't freeze up a slow user's browser?) Also, could you elaborate about how event.target works?

It may very well slow the performance of a page with 30,000 words. I'd argue that is excessive and probably would benefit from being paginated, but I don't know your exact circumstances.

event.target property holds the element that started the event - the event bubbles up / propagates to its parent, which then handles the event, so you don't have 30,000 events on separate span elements.

这篇关于得到单词点击段落的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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