[英]Replace text in html textarea
我有这个脚本,如果在减号之间,则与textarea中keyup上的文本匹配。
$('#notes').keyup(function() { // notes is the id of the textarea
var regex = /\-([^\)]+)\-/gmi; // it gets the text between minus sign. Example: -text-
var myValue = $(this).val();
if(myValue.match(regex)){
var reference = myValue.match(regex);
$.ajax({
async: false,
type: "POST",
url: "scripts/script.php",
data: { "reference" : reference },
success: function(data) {
// I need to replace the text matched by the regex with data in the textarea.
// I need to stop the ajax calling after success or call it only if regex is matched
}
});
}
});
当文本与正则表达式匹配时,它将向脚本发送ajax post调用,该脚本在数据库中搜索世界并返回定义。 我需要将正则表达式匹配的文本替换为数据,即数据库提取的定义。
另外,我只想在匹配正则表达式时启动ajax POST调用。 它只是第一次工作。 第一次比赛后,它仍会为每个按键发送呼叫。
试试下面的代码。
var triggerTime;
$("#notes").keyup(function() { // notes is the id of the textarea
clearTimeout(triggerTime);
var myValue = $(this).val();
triggerTime = setTimeout(function(){
var regex = /\-([^\)]+)\-/gmi; // it gets the text between minus sign. Example: -text-
if(myValue.match(regex)){
var reference = myValue.match(regex);
$.ajax({
async: false,
type: "POST",
url: "scripts/script.php",
data: { "reference" : reference },
success: function(data) {
// I need to replace the text matched by the regex with data in the textarea.
// I need to stop the ajax calling after success or call it only if regex is matched
}
});
}
}, 3000);// Call request in 3 second
});
这是代码的优化版本。 它会等待用户完成操作,并且在3秒钟内处于不活动状态时,它将生成Ajax调用。
您可以将频率更改为2000或1000(分别为2秒和1秒)。
我解决了将contenteditable =“ true”添加到文本区域的问题。 在最终的jquery代码下面:
var textInput = $("#notes"); // the ID of the textarea
var triggerTime;
$("#notes").keyup(function() { // notes is the id of the textarea
clearTimeout(triggerTime);
var myValue = $(this).text();
triggerTime = setTimeout(function(){
var regex = /\-([^\)]+)\-/gmi; // it gets the text between minus sign. Example: -text-
if(myValue.match(regex)){
var newValue;
var reference = myValue.match(regex);
$.ajax({
async: false,
type: "POST",
url: "scripts/parser.php",
data: { "reference" : reference },
success: function(data) {
newValue = data;
console.log(newValue);
$('.textarea').html(function() {
return $(this).text().replace(reference[0], '<strong>' + newValue + '</strong>');
});
}
});
}
}, 1000);// Call request in 1 second
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.