我有一個使用凱撒密碼加密文本的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(""));
}