2016-04-30 14 views
0

私は一種の基本的なスペルチェッカーを設計しています。私は以下の内容をdiv要素があるとします。div内のn番目の単語の周りにスパンを挿入します

<div>This is some text with xyz and other text</div> 

私のスペルチェッカーが正常に起因する(例の場合には(単語の5をDIV(current_objectと題したjQueryオブジェクトを返す)とインデックスを特定0から始まる))。

私が今やりたいことは、この単語をスパンで囲みます。

<div> 
    This is some text with 
    <span class="spelling-error">xyz</span> 
    and other text 
</div> 

は、しかし、私は、例えば行うメソッドを呼び出す/キャレットを移動する/既存のユーザの選択を変更することなく、これを実行する必要があります。

<span class="spelling-error">xyz</span> 

このような最終的な構造で私を残し言い換えれば

window.getSelection().getRangeAt(0).cloneRange().surroundContents(); 

ユーザーがcontenteditable文書に第四のdivに取り組んでいる場合は、私のコードは、他のdiv内の問題を識別う - 第四DIVからフォーカスを削除していない間(第一第三に)。

多くの感謝!

答えて

1

あなたはこの投稿をjQueryとタグ付けしましたが、特に使用する必要はないと思います。私はあなたに例を書いた。

https://jsfiddle.net/so0jrj2b/2/

// Redefine the innerHTML for our spellcheck target 
spellcheck.innerHTML = (function(text) 
{ 
    // We're using an IIFE here to keep namespaces tidy. 

    // words is each word in the sentence split apart by text 
    var words = text.split(" "); 
    // newWords is our array of words after spellchecking. 
    var newWords = new Array; 

    // Loop through the sentences. 
    for (var i = 0; i < words.length; ++i) 
    { 
    // Pull the word from our array. 
    var word = words[i]; 

    if (i === 5) // spellcheck logic here. 
    { 
     // Push this content to the array. 
     newWords.push("<span class=\"mistake\">" + word + "</span>"); 
    } 
    else 
    { 
     // Push the word back to the array. 
     newWords.push(word); 
    } 
    } 

    // Return the rejoined text block. 
    return newWords.join(" "); 
})(spellcheck.innerHTML); 

彼女は簡単にそれをより有効に活用するために、独自の関数の宣言にそのロジックを移動することで再現できる生命維持の私の使用を注目に値します。

スペルチェックインスタンスの句読点も考慮する必要があることに注意してください。

+0

ありがとうございました!理想的な解決策。追加する唯一の方法は、おそらくvar words = text.split( "")を正規表現に置き換えて単語を決定することでしょうか? – John1984

+1

はい、私はあなたができると信じています。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split – Josh

関連する問題