2014-10-12 50 views
-1

我正在創建一個網頁來計算簡單的凱撒密碼而不使用jquery。我找不到錯誤,我不確定如何將新字符串返回到文本區域。JavaScript中的凱撒密碼返回意想不到的結果

HTML:

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

的javascript:

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 2014-10-12 04:22:50

+0

我不需要這個,但我仍然習慣於最後的java編程課。 – 2014-10-12 04:30:20

+0

有兩件事情:你能更清楚地知道什麼是攻擊,什麼是實際問題(例如預期與意外行爲,實際錯誤消息等)。其次,我這次爲你做了,請在發佈時正確地設置你的代碼。請記住,如果您希望其他人提供幫助,使您的代碼看起來不錯並且乾淨(正確的縮進等)可顯着改善此體驗。 – 2014-10-12 04:35:53

回答

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

代碼和解釋很少有幫助 – 2014-10-12 04:52:54

+0

@FelixKling它與TS'是相同的代碼,只是寫略有不同,他會看到問題區域的差異。 – Cheery 2014-10-12 04:56:51