gpt4 book ai didi

jquery - 使用 jQuery 选择双击单词的所有实例

转载 作者:行者123 更新时间:2023-12-01 03:51:19 25 4
gpt4 key购买 nike

我对 JQuery 还很陌生。我在 div 中有一段文字。当用户双击一个单词时,我想选择所有单词的外观。问题是我不知道如何引用所选的单词。有谁能够帮助我?提前致谢

最佳答案

这似乎有效: http://jsfiddle.net/f3wzT/

代码找到双击的单词,然后将该单词的所有实例包装在一个跨度中。可能有更好的方法来做到这一点,但是,正如您从上面的 jsFiddle 中看到的,这确实有效。

这是代码(从多个来源快速拼凑而成):

<script type="text/javascript">
function getSelectedText() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
} else if (document.getSelection) {
txt = document.getSelection();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
return txt;
}

function deselectText() {
if (window.getSelection) {
window.getSelection().removeAllRanges();
} else if (document.getSelection) {
txt = document.getSelection().removeAllRanges();
} else if (document.selection) {
txt = document.selection.empty;
}

}

$(document).ready(function() {
$('#content').dblclick(function() {
$('.highlight').removeClass('highlight');
var t = getSelectedText();
var regex = new RegExp(t, "gi");
this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"highlight \">" + matched + "</span>";});
deselectText();
});

});
</script>

关于jquery - 使用 jQuery 选择双击单词的所有实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8358343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com