2014-10-12 2 views
-1

jquery를 사용하지 않고 간단한 시저 암호를 계산하는 웹 페이지를 만듭니다. 오류를 찾을 수 없으며 새 문자열을 텍스트 영역으로 반환하는 방법을 모르겠습니다.JavaScript에서 Caesar 암호가 예기치 않은 결과를 반환합니다.

HTML :

<input type="button" value="Encrypt value = 1" onclick ="caesarEncipher(shift, text)"/> 

자바 스크립트 :

function caesarEncipher(shift, plaintext) { 
    this.shift = shift; 
    this.plaintext = plaintext; 
    var ciphertext 

    for (var i = 0; i < plaintext.length; i++) { 
    // ASCII value - get numerical representation 
    // 65 = 'A' 90 = 'Z' 
    var encode = plaintext.charCodeAt(i); 
    if (encode >= 65 && encode <= 90) 
     // Uppercase 
     ciphertext += String.fromCharCode((encode - 65 + shift) % 26 + 65); 
     // 97 = 'a' 122 = 'z' 
    else if (encode >= 97 && encode <= 122) 
     // Lowercase 
     ciphertext += String.fromCharCode((encode - 97 + shift) % 26 + 97); 
    else 
     ciphertext += input.charAt(i); 
    } 
    return document.getElementById = ciphertext; <-- Not sure about this 
} 
+0

가 왜'this.' 여기에 필요합니까? – Cheery

+0

이 코드는 필요하지 않지만 마지막 자바 프로그래밍 클래스에는 익숙합니다. –

+0

두 가지 : 해핑이 무엇인지, 실제 문제가 무엇인지 (예 : 예상치 못한 행동, 실제 오류 메시지 등)에 대해 더 명확하게 표현할 수 있습니까? 둘째로, 나는이 시간 동안 해 주셨습니다. 게시 할 때 코드를 올바르게 포맷하십시오. 다른 사람들이 도움을 원한다면 코드를 멋지고 깨끗하게 보이게 (적절한 들여 쓰기 등)하면 그 경험이 크게 향상됩니다. –

답변

0

http://jsfiddle.net/y9rv6bux/

function encrypt(id, shiftId) 
 
{ 
 
    var t = document.getElementById(id), out = ''; 
 
    var shift = parseInt(document.getElementById(shiftId).value); 
 
    var txt = t.value, ranges = [[65,90],[97,122]]; 
 
    
 
    for(var i = 0; i < txt.length; i++) 
 
    { 
 
     var code = txt.charCodeAt(i); 
 
     for(var j = 0; j < ranges.length; j++) 
 
     { 
 
      if (code >= ranges[j][0] && code <= ranges[j][1]) 
 
      { 
 
       code = ((code - ranges[j][0] + shift) % 
 
        (ranges[j][1] - ranges[j][0] + 1)) + ranges[j][0]; 
 
       break; 
 
      } 
 
     } 
 
     out += String.fromCharCode(code); 
 
    } 
 
    t.value = out; 
 
}
<textarea id='t'></textarea><br><input type='text' id='s' value='1'><br> 
 
<input type='button' onclick='encrypt("t", "s")' value='Go'>

+0

설명이있는 코드는 거의 도움이되지 않습니다 .. –

+0

@FelixKling은 'TS와 동일한 코드입니다. 약간 다른 방식으로. 그는 문제가있는 분야의 차이점을 보게 될 것이다. – Cheery

관련 문제