2010-05-23 3 views
3

내 목표 : 사용자가 텍스트를 선택하고 버튼을 클릭 할 때마다 해당 텍스트가 배열에 추가됩니다. 문제 : 버튼을 누를 때마다 배열의 모든 객체가 현재 선택된 텍스트로 덮어 쓰기됩니다.자바 스크립트 : 선택한 텍스트를 배열에 추가

선택한 텍스트가 이전의 모든 배열 항목을 덮어 쓰지 않도록 동작을 변경하는 데 도움을 주셔서 감사합니다.

<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> 

답변

3

window.getSelection() 선택 객체가 아닌 문자열을 반환합니다,하지만처럼 보인다 당신이 그것을 인쇄 할 때 문자열. 그런 다음 배열에는 해당 선택 개체에 대한 참조가 있습니다. 다음에 선택 객체가 변경되면 배열 참조도 변경됩니다. 선택 개체를 배열에 넣을 때 선택 개체를 문자열로 변환하려고합니다.

selects.push (""+ txt);

... + 비트는 + 연산자를 통해 선택 개체를 문자열로 변환합니다. 그것을 할 다른 (더 좋은) 방법이있을 수 있습니다 ...

1

편집 나는 :-) AAA를 파악하기 때문에! 밟아 다진!!!

해당 창 선택 개체를 직접 가져올 때 불변의 불변 문자열을 차지하지 않습니다. 너는 하나 만들어야 해.

 txt = '' + window.getSelection(); 

또는 당신을 "선택"을 추가 할 때 : 다음과 같이 "TXT"로 설정하십시오

 selects.push('' + txt); 
+0

고마워, 내가 디버깅하는 데 사용했던 '바보 같은 코드'를 꺼냈다. 문자열을 출력 할 수 없습니다. 각 항목을 별도의 값으로 유지해야하므로 나중에 텍스트를 찾을 수 있습니다. – joeybaker

관련 문제