2016-01-22 77 views
0

現在我有一個可編輯的DIV。我已經能夠很容易地獲得char索引,但是我無法將它插入正確的位置。我可以使用拼接插入它,只要沒有HTML元素就可以工作。那麼我將如何去忽略標籤呢?看起來使用正則表達式可能是可能的,但是處理過多。看起來我可以使用Range,但是我在理解JavaScript範圍方面遇到了很多麻煩。以下是基本思想:Javascript插入元素的字符引用可編輯的DIV與子元素

<div class="toinsert" contenteditable="true">Some Text <strong>here</strong></div> 

var charisat = 8; //SOME NUMBER 

var dividedcontent = []; //DIVIDE CONTENT, BY RANGE OR REGEX 

$('.toinsert').html(dividedcontent[0] + '<em>other text</em>' + dividedcontent[1]); 
+0

無法理解你的問題,請提供_Current輸出(也許這是失敗的)_和_Expected output_ – Rayon

回答

1

不知道是否有更好的辦法,但粗暴的方式會像

var charisat = 8; 
 
addContent($('<em>other text</em>'), charisat, $('.toinsert')) 
 

 

 
function addContent($content, pos, $el) { 
 
    $el.contents().each(function() { 
 
    if (this.nodeType == Node.TEXT_NODE) { 
 
     var text = $(this).text(); 
 
     if (text.length >= pos) { 
 
     var $obj = $(); 
 
     $obj = $obj.add(document.createTextNode(text.substring(0, pos))); 
 
     $obj = $obj.add($content); 
 
     $obj = $obj.add(document.createTextNode(text.substring(pos))); 
 
     $(this).replaceWith($obj); 
 
     return; 
 
     } else { 
 
     pos -= text.length; 
 
     } 
 
    } else if (this.nodeType == Node.ELEMENT_NODE) { 
 
     pos = addContent($content, pos, $(this)); 
 
    } 
 
    return pos; 
 
    }) 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="toinsert" contenteditable="true">Some Text <strong>here</strong> 
 
</div>

+0

https://jsfiddle.net/arunpjohny/qjmtL8dk/ –

+0

這絕對有效。我只是希望有一個更簡單的方法。謝謝。 –

+0

@JustinLevine你永遠不能使用RegEx可靠的HTML標記,所以另一種我唯一看到的就是處理012om –