2017-03-12 37 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')); 
相关问题