簡體   English   中英

Javascript:將選定的文本添加到數組中

[英]Javascript: Adding selected text to an array

我的目標:每次用戶選擇文本並單擊按鈕時,該文本都會添加到數組中。 問題:每次按下按鈕,數組的所有對象都會被當前選定的文本覆蓋。

我非常感謝幫助更改行為,以便所選文本不會覆蓋所有以前的數組項。

<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()返回一個選擇對象,而不是一個字符串,但在打印出來時它看起來像一個字符串。 然后,該數組具有對該選擇對象的引用。 下次選擇對象更改時,數組引用也會更改。 您希望在將選擇對象放入數組時將其轉換為字符串:

selects.push( “” + TXT);

...“+”通過+運算符將選擇對象轉換為字符串。 可能還有另一種(更好的)方法......

編輯,因為我想出來:-) aaa! 挨打!

當你直接抓取那個窗口選擇對象時,你並沒有抓住一個干凈的不可變字符串。 你需要制作一個。 嘗試像這樣設置“txt”:

     txt = '' + window.getSelection();

或者當您將其添加到“選擇”時:

     selects.push('' + txt);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM