2016-12-09 8 views
1

でHTMLを追加:私はのcontentEditableとDIVた特定の位置

<div class="example" contenteditable="true">This is an example</div> 

innerHTMLを使用して、私は "これは一例です" を取得。今

第七位で(右後に「ある」)キャレット位置を知る( - ない何clickfocusを使用してのいずれか)

<div class="example" contenteditable="true">This is <span class="yup">NOT</span> an example</div> 

、私は以下を与えるために、HTML(<span class="yup">NOT</span>)を追加したいですand innerHTML、どうすればhtmlを追加できますか?

私はsubstrを使用し、次に.html(content)を使用することを考えましたが、それはコンテンツ全体を置き換えており、避けたいのです。私は単に特定の位置に直接コンテンツを追加したいと思います。

たとえば、コンテンツ全体を置き換えることと、したくないことを置き換えること。

置き換えるのではなく、ちょうど "注入"したいと思います。

ご提案は大変ありがとうございます。

+0

私が試した例を追加しました(これは内容全体と私がやりたくないことを置き換えます)。 –

+0

私はあなたがテキストノードの真ん中に "注入"することができないかどうかはわかりません。私はあなたがおそらく交換する必要があると思う... –

+2

[textNode値の変更]の可能な複製(http://stackoverflow.com/questions/680431/change-textnode-value) –

答えて

1

JavaScriptでは文字列は変更できません。新しい文字列を作成せずに内容を変更することはできません。

これはあなたが得ることができるくらい近くにあります(substrsubstring)。

// Store the new data 
 
var newOutput = " <span class='yup'>NOT</span> "; 
 

 
// Get a reference to the target div 
 
var theDiv = $("div.example"); 
 

 
// Split the current content of the div where there are spaces 
 
// and return the individual words into a new array 
 
var words = theDiv.text().split(/\s+/g); 
 

 
// Inject the right pieces of the array along with spaces and the new content 
 
// into the div 
 
theDiv.html(words[0] + " " + words[1] + newOutput + words[2] + " " + words[3]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="example" contenteditable="true">This is an example</div>

しかし、あなたは純粋なJavaScriptからdivのコンテンツを生成する機会を持っている場合、あなたはので、このスニペットを実行し、数回(このように、一度だけ、正しい文字列を挿入することができます様々な乱数が生成されるたびにdivのコンテンツの変化を見ることができます)。

// Store the new data 
 
var output1 = "This is an example."; 
 
var output2 = "This is <span class='yup'>NOT</span> an example."; 
 

 
// Get a reference to the target div 
 
var theDiv = $("div.example"); 
 

 

 
// Inject the correct string into the div based on some criteria 
 
var x = Math.random() > .5; 
 
x === true ? theDiv.html(output1) : theDiv.html(output2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="example" contenteditable="true">This is an example</div>

+0

コンテンツを特定の場所に挿入する代わりに、コンテンツ全体を置き換えることができます。 –

+0

また、元の文字列全体を置き換えることなく、文字列を別の文字列に挿入することはできません。どのようにスライスしても(punが意図されていなくても)、 'div'のテキスト内容を変更するには、古い文字列がなくなり、新しい文字列が必要になります。 –

+0

Mhmm、分かります。別の方法を調べる。ありがとう。 –

3

あなたは全体の内容を設定することなく、要素のHTML文字列を変更することはできません。すでに<span class="yup">NOT</span>を置いておくことをお勧めしますが、CSSで見えなくすることをお勧めします。その後、それがトグルされている場合は、Javascriptで表示するだけです。

+0

アップアップされましたが、本当に必要なものではありません。ありがとう。 –

関連する問題