问题描述
我有这个脚本,如果在减号之间,则与textarea中keyup上的文本匹配.
I have this script that matches a text on keyup in a textarea if between the minus sign.
$('#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调用发送到脚本,该脚本在数据库中搜索世界并返回定义.我需要将正则表达式匹配的文本替换为数据,即数据库提取的定义.
When text is matched by the regex it send an ajax post call to a script that search the world in a database and returns a definition. I need to replace the text matched by the regex with data, the definition extracted by the database.
此外,我只想在正则表达式匹配的情况下启动ajax POST调用.它只是第一次工作.第一次比赛后,它仍会为每个按键发送呼叫.
Additionally I'd like to launch the ajax POST call only if regex is matched. It works just the first time. After first match it still sending the call for each keyup.
推荐答案
我解决了向文本区域添加 contenteditable ="true" 的问题.在最终的jquery代码下面:
I solved the problem adding contenteditable="true" to the textarea.Below the final jquery code:
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
});
这篇关于替换html textarea中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!