使用鼠标在文本jquery中仅选择一个单词 [英] Use the mouse to select only one word in text jquery
本文介绍了使用鼠标在文本jquery中仅选择一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究Rails 4项目.我只需要从一个段落中选择一个单词.现在,我可以使用以下代码选择整个段落:
I am working on rails 4 project. I need to select only one word from a paragraph. Right now i am able to select the entire paragraph using the below code:
function SelectText(element) {
var doc = document,
text = doc.getElementById(element),
range,
selection;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
$(function() {
$('p').click(function() {
SelectText('selectme');
});
});
是否有任何方法可以修改此代码以从段落中仅选择一个单词?
Is there any way to modify this code to select only one word from the paragraph?
推荐答案
我将上面注释中链接的两个StackOverflow问题与您提供的代码合并在一起.这是代码和JSFiddle的结果:
I merged the two StackOverflow questions I linked to in the comment above with the code you provided. Here's the result in code and a JSFiddle:
$(document).ready(function()
{
var words=$("#yourTextContainer").text().split(' ');
$("#yourTextContainer").html("");
$.each(words, function(i,val)
{
//wrap each word in a span tag
$('<span/>').text(val +" ").appendTo("#yourTextContainer");
});
$("#yourTextContainer span").live("click",function(event)
{
event.stopPropagation();
SelectText($(this));
});
});
function SelectText(element)
{
var doc = document,
text = element.get(0),
range,
selection;
if (doc.body.createTextRange)
{
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
}
else if (window.getSelection)
{
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
这篇关于使用鼠标在文本jquery中仅选择一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文