選択できるようにしたい大きなテキストがあり、選択した部分をstartindex
andで保存しますendindex
。(たとえば、or
inword
を選択すると mestartindex
1
と endindexが返され2
ます。)
これはすべて正常に動作しますが、&
(アンパサンド) などの HTML エンティティに問題があります。
私は問題が構成されている小さなケースを作成しました。以下のフィドルで、 を超えるものを選択すると が膨張することがstartIndex
わかります。&
&
&
インデックスを台無しにすることなく、アンパサンドなどの特殊文字を適切にカウントする方法はありますか?
JavaScript
$(document).ready(function() {
$('#textBlock').mouseup(function() {
var selectionRange = window.getSelection();
if (!selectionRange.isCollapsed) {
selectedText = selectionRange.getRangeAt(0).toString();
}
document.getElementById('textBlock').setAttribute('contenteditable', true);
document.execCommand('strikethrough', false);
var startIndex = $('#textBlock').html().indexOf('<strike>');
$('#startindex').html('the startindex is: ' + startIndex);
done();
});
});
function done() {
document.getElementById('textBlock').setAttribute('contenteditable', false);
document.getSelection().removeAllRanges();
removeStrikeFromElement($('#textBlock'));
}
function removeStrikeFromElement (element) {
element.find('strike').each(function() {
jQuery(this).replaceWith(removeStrikeFromElement(jQuery(this)));
});
return element.html();
}
私はそれが の代わりに$('#textBlock').html()
を行うことに関係していると思う/知っている. andを取得する最善の方法は、選択したテキストを通過することでした。これは、アプリケーションで使用されることのない HTML タグであるためです。indexOf
text()
start
endindex
<strike>
execCommand