gpt4 book ai didi

jquery - 添加指向句子中某个单词的链接

转载 作者:行者123 更新时间:2023-12-01 04:56:48 24 4
gpt4 key购买 nike

JQuery 中有没有一种方法可以从用户输入的句子中选择特定的单词,并且他可以添加指向该单词的链接。注意:该句子不是硬编码的,我们不这样做不知道用户会输入哪个句子。根据句子,我们必须创建指向所选单词的链接。

最佳答案

合并来自 Use JavaScript and jQuery to Get User Selected Text, and then Do Something (Useful?) With It 的资源, wrapping text using jQuery以及下面 Sridhar Narasimhan 的回答部分,您可以得出以下结果(未经测试):

HTML:

<input type="text" id="enter"/>
<div id="content" ></div>
<div id="link" ></div>

Javascript:

$("#enter").bind("keyup", function() {
$("#content").html($("#enter").val());
});

$.expr[":"].containsNoCase = function(el, i, m) {
var search = m[3];
if (!search) return false;
// we'll use text to find what we want...
return eval("/" + search + "/ig").test($(el).text());
};


if (!window.Kolich) {
Kolich = {};
}

Kolich.Selector = {};
Kolich.Selector.getSelected = function() {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}

$.expr[":"].containsNoCase = function(el, i, m) {
var search = m[3];
if (!search) return false;
// we'll use text to find what we want...
return eval("/" + search + "/ig").test($(el).text());
};


Kolich.Selector.mouseup = function() {
var st = Kolich.Selector.getSelected();
if (st != '') {
// alert("You selected:\n" + st);
// wrap selecetd word in a link
$("#content:containsNoCase('" + st + "')").each(function() {
var textwithLink = '<a href="javascript:alert(\'link-to-selected-text.htm\')">' + st + '</a>';

$("#link").html(textwithLink);

});
}
}

$(document).ready(function() {
$(document).bind("mouseup", Kolich.Selector.mouseup);
});

WORKING DEMO

关于jquery - 添加指向句子中某个单词的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13799541/

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