xmlhttprequest
을 사용하여 사전 파일을로드 할 수 있으며로드가 완료되면 배열에 덤프 할 수 있습니다. 그런 다음 키가 해제 될 때마다 (또는 단어의 철자를 검사하려고 할 때) 단어를 사전의 단어와 비교하는 함수를 호출 할 수 있습니다.
이
HTML :
<textarea onkeyup="check(this)"></textarea>
자바 스크립트가 :
//A large array of dictionary words
var dictionary = new Array();
//First, let's load up the dictionary
address = "words.txt";
//Create an XMLHTTPRequest object
var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
if(req == null) {
console.log("Error: XMLHttpRequest failed to initiate.");
}
//When it loads, add all the elements to the dictionary array
req.onload = function() {
dictionary = req.responseText.split("\n");
//Convert all the characters to lowercase. That way, multi-case strings are allowed.
for(var i = 0; i < dictionary.length; i++)
dictionary[i] = dictionary[i].toLowerCase();
}
try {
req.open("GET", address, true);
req.send(null);
} catch(e) {
console.log("Oh snap");
}
//This function is called every time a key is released
function check(element) {
var allWords = element.value.split(" ");
for(var i = 0; i < allWords.length; i++) {
if(dictionary.indexOf(allWords[i].toLowerCase()) == -1) {
element.style.backgroundColor = "#FFF";
return;
}
}
element.style.backgroundColor = "#0F0";
}
편집 : 텍스트 영역에 대한 작동하도록 코드를 수정
@ JeffreySweeny : 여러 단어가 어떨까요? – Bytemain
@ David. 당신이 말하는 것을 이해하고 있다고 가정 할 때 여전히 작동합니다. 'indexOf' 함수는 단어가 사전에 전혀 존재하지 않으면 -1을 반환합니다. 사용자가 "사과 사과"를 입력하면 여전히 작동합니다. 그러나이 코드에는 이중 공백이나 새 줄과 같은 문제가 없습니다. 수정하기는 쉽지만 예제에서는 추가 코드가 필요하지 않습니다. –
이것은 훌륭합니다! 그래서 이것을 올바르게 읽는다면 단순히 html 텍스트 상자를 만들고이 JavaScript를 연결해야합니다. 그러면 제대로 작동합니까? 이 경우에 사용되는 사전의 관점에서 "words.txt"는 각 단어 사이에 구분 기호가 필요합니다. 현재 "words.txt"는 기본적으로 하나의 매우 긴 단어이며 공백을 포함하지 않으므로 –