[英]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.