我有虚拟文本,我希望将每个突出显示的文本选择存储在带有vanilla javascript的数组中。
这是我在另一个textarea标签中显示单个选择的第一个试验。
<div>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure sed ea aperiam voluptas error assumenda iusto, sequi unde non, nesciunt autem. Atque eveniet delectus tenetur nostrum quaerat explicabo debitis iste.
Ipsa a nobis voluptatem dolores ducimus reiciendis iste unde, dolorum ut eveniet inventore consequatur illum provident similique quas rem quidem odit officiis eaque illo impedit tenetur quam atque ab! Velit!
Commodi voluptas saepe cupiditate mollitia. Dolores delectus explicabo laborum exercitationem suscipit ullam quod dignissimos molestiae? Animi, commodi quod vel nesciunt ab possimus nostrum explicabo fugiat tenetur magni dolor illo aliquam?
</div>
<textarea
type='text'
id='input'>
</textarea>
<script>
var text = []
function gText (e) {
text = (document.all) ? document.selection.createRange().text : document.getSelection()
document.getElementById('input').value = text
}
document.onmouseup = gText
if (!document.all) document.captureEvents(Event.mouseup)
</script>
现在我猜我需要用数据推送数组上的每个选项 foreach循环但我真的不知道如何在没有jquery的情况下执行此操作。有什么帮助吗?
答案 0 :(得分:1)
如果我理解你正确,你想存储在页面上做出的任何选择的价值?如果是的话......
<script>
/**
* Store selection in an array and only store same value once.
*/
var selectionArray = [];
function storeSelection(e){
var selectedText = window.getSelection().toString();
if(selectedText.length && selectionArray.indexOf(selectedText) === -1){
selectionArray[selectionArray.length] = selectedText;
}
console.log(selectionArray);
}
document.addEventListener('mouseup', storeSelection);
</script>