gpt4 book ai didi

javascript - 如何一一创建文本并返回修复拼写

转载 作者:行者123 更新时间:2023-11-28 06:35:55 24 4
gpt4 key购买 nike

我在占位符中插入了一段文本。并且它工作正常。现在出现文本后,我希望光标转到特定点(这里是疑问)并更正拼写错误的单词(怀疑到怀疑)。

怎么做?你能给我展示我想在元素中做的任何示例吗?

代码###

var txt = "Please write your message.If any doubts, don't hesitate to make a questions !";
var timeOut;
var txtLen = txt.length;
var char = 0;
$('textarea').attr('placeholder', '|');
(function typeIt() {
var humanize = Math.round(Math.random() * (200 - 30)) + 30;
timeOut = setTimeout(function() {
char++;
var type = txt.substring(0, char);
$('textarea').attr('placeholder', type + '|');
typeIt();

if (char == txtLen) {
$('textarea').attr('placeholder', $('textarea').attr('placeholder').slice(0, -1)) // remove the '|'
clearTimeout(timeOut);
}

}, humanize);
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<textarea cols="50" rows="15" placeholder=""></textarea>
</form>

最佳答案

首先,添加另一个变量来保存修改后的、无拼写错误的字符串,以便我们仍然可以迭代原始字符串。这个新变量将用于显示文本。

var modified_txt = "";

如果您知道拼写错误在字符串中的位置,您可以创建一个拼写错误位置的对象来检查。

//Positions in the txt string where typos exist
var typos = {
38: {},
25: {}
}

随着字符计数器的增加,您可以对照对象检查它。

var test = typos[char];
if (test !== undefined) {
//Typo found do something with it
}

在本例中,我选择编写 2 个新函数,1 个用于添加字符,1 个用于删除字符

function deleteCharacter(text) {
text = text.substring(0, text.length - 1);
return text;
}

function addCharacter(text, character_added) {
text = text + character_added;
return text;
}

我还决定让拼写错误对象属性之一成为一个函数,这样我们就可以组织拼写错误并在拼写错误对象中执行我们想要的操作。

var typos = {
38: {
error: 's',
correction: function(text) {
var temp = deleteCharacter(text);
$('textarea').attr('placeholder', temp + '|');
return temp;
}
}
}

现在我们可以在发现拼写错误时进行函数调用。

if (test !== undefined) {
//Typo found do something with it
setTimeout(function() {
var chunk_one = test.correction(modified_txt);
modified_txt = chunk_one;
char++;
typeIt();
}, humanize());
} else { //If no typos are found then move to the next character
setTimeout(function() {
char++;
typeIt();
}, humanize());
}

Full working code at codepen

关于javascript - 如何一一创建文本并返回修复拼写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34285543/

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