简体   繁体   English

Javascript:将选定的文本添加到数组中

[英]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. window.getSelection()返回一个选择对象,而不是一个字符串,但在打印出来时它看起来像一个字符串。 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); 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! 编辑,因为我想出来:-) 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”:

     txt = '' + window.getSelection();

or when you add it to "selects": 或者当您将其添加到“选择”时:

     selects.push('' + txt);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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