Заменить текст в HTML текстовой области
У меня есть этот сценарий, который соответствует тексту на клавиатуре в текстовой области, если между знаком минус.
$('#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 скрипту, который ищет мир в базе данных и возвращает определение. Мне нужно заменить текст, соответствующий регулярному выражению, данными, определением, извлеченным из базы данных.
Кроме того, я хотел бы запустить вызов ajax POST, только если сопоставлено регулярное выражение. Это работает только в первый раз. После первого матча он по-прежнему отправляет вызов для каждого ключа.
2 ответа
Я решил проблему с добавлением 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
});
Попробуйте приведенный ниже код.
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 секунда соответственно).