2017-03-12 65 views
0

我有一個使用凱撒密碼加密文本的JavaScript函數。如何在控制檯中保留消息? (JS功能)

我也有發送數據到PHP的HTML形式中,PHP使用echo到其打印成div元素,然後,WHE我按另一個button(未輸入),它調用「凱撒加密」功能(其用DOM接收div的值)。

問題是,當函數執行它的工作時,它使用console.log將它打印到控制檯中 - 但是當它打印時,它只會持續半秒,然後消息消失。

我認爲它與頁面重新載入或某事有關,所以如果你可以請解釋我該如何解決它,以及爲什麼 - 我非常感謝你!

HTML & PHP:

<form style="display: inline-block" method="get" action="index.php"> 
    <fieldset> 
     <legend>Caesar Cipher</legend> 
     <input type="text" name="text"> 
     <input type="number" name="shift"> 
     <input type="submit" name="submit"> 
     <button onclick="caesarCipher(1)">Encrypt</button> 
      //the value 1 means that the function will encrypt, and not decrypt 
    </fieldset> 
</form> 

<div id="text"> 
    <?php 
     if(isset($_GET["submit"])) { //when the submit (input) button is pressed 
      $text = $_GET["text"]; 
      echo htmlspecialchars($text); 
       //set div (id="text") innerHTML (DOM) the value of the input field 
     } 
    ?> 
</div> 

的JavaScript:

function caesarCipher(dir) { 
    //the function takes a text, enters every letter into an array, 
    //and then shifts it using the letters array (with their index) 
    //it logs the array (array.join("")) into the console - here is the problem 

    text = document.getElementById("text").innerHTML.trim().toLowerCase(); 
    shift = 3; 
    var letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]; 
    var charArray = []; 
    for(var i = 0; i < text.length; i++) { 
     var letter = text.charAt(i); 
     if(letter == " ") 
      letter = " "; 
     else { 
      var index = letters.indexOf(letter); 
      if(dir > 0) 
       index = (index + shift) % 26; 
      else { 
       index -= shift; 
       if(index < 0) 
        index += 26; 
      } 
     letter = letters[index]; 
     } 
     charArray[i] = letter; 
    } 
    console.log(charArray.join("")); 
} 

回答

0

勾選保留日誌複選框。

此外,

<!-- This is how you comment in HTML --> 
1

在谷歌瀏覽器,你可以按F12Ctrl+Shift+J鍵顯示側邊欄的圖片和檢查Preserve Log複選框以保存日誌消息。

enter image description here

類似的選項存在於其他瀏覽器也。

0

爲什麼不使用localStorage

localStorage.setItem('encString', charArray.join("")); 
// whenever you want to see it, even after a window reload 
console.log(localStorage.getItem('encString')); 
相關問題