简体   繁体   中英

Javascript: Adding selected text to an array

My goal: each time a user selects text, and clicks a button, that text gets added to an array. The problem: each time the button is pressed, the all objects of the array get overridden with the currently selected text.

I'd really appreciate help changing the behavior so that the selected text doesn't override all previous array items.

<script type="text/javascript">
  var selects = new Array();
  selects.push("1");
  function getSelText()
{
    var i = 0;
    while (i<1) {
    var txt = [null];
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection)
    {
        txt = document.getSelection();
            }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
    }
    else return;
    selects.push(txt);
    i++;
    };
document.menu.selectedtext.value = selects;
}
</script>


<form class="menu" name="menu">
  <input type="button" value="highlight" class="highlightButton" onmousedown="getSelText()"/>
  <textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

window.getSelection() returns a selection object, not a string, but it looks like a string when you print it out. Then, the array has a reference to that selection object. Next time the selection object changes, so does the array reference. You want to convert the selection object to a string when you put it into the array:

selects.push(""+txt);

... the ""+ bit, through the + operator, converts the selection object to a string. There may be another (better) way to do it...

edit because I figured it out :-) aaa! beaten!!!

When you grab that window selection object directly, you're not grabbing a clean immutable string. You need to make one. Try setting "txt" like this:

     txt = '' + window.getSelection();

or when you add it to "selects":

     selects.push('' + txt);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM