我在html textarea中有一个字符串。使用jquery可以通过单击单词从字符串中选择一个单词。
答案 0 :(得分:4)
这不完全是你想要的,但我希望它能以某种方式帮助你...我从网上得到了这个。
$(document).ready(function() {
$('body').on('click', 'textarea', function() {
textarea_Click(this);
});
});
function textarea_Click(e) {
var caret = getCaretPosition(e);
var text = e.value;
var begin = caret - 1;
while (begin >= 0) {
if (text.charAt(begin) == '}') return;
else if (text.charAt(begin) == '{') break;
else begin--;
}
if (begin >= 0) {
var end = caret;
while (end < text.length) {
if (text.charAt(end) == '}') break;
else end++;
}
if (end < text.length)
setSelection(begin, end, e);
}
}
function getCaretPosition(textarea) {
if (textarea.selectionStart) {
return textarea.selectionStart;
} else {
// TODO: Handle IE ugliness on your own :)
return 0;
}
}
function setSelection(begin, end, textarea) {
if ("selectionStart" in textarea) {
textarea.selectionStart = begin;
textarea.selectionEnd = end + 1;
} else if (document.selection) {
// TODO: Handle IE ugliness on your own :)
return;
}
}
textarea {
width: 100%;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<textarea>Our doubts are traitors, {and} make us lose the {good} we oft might win, by {fearing} to attempt.</textarea>