开发者

Javascript: Adding selected text to an array

开发者 https://www.devze.com 2022-12-31 03:29 出处:网络
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 curren

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.cre开发者_JAVA百科ateRange().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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号