【问题标题】:How to define textbox input as a string in JavaScript?如何在 JavaScript 中将文本框输入定义为字符串?
【发布时间】:2019-06-03 12:42:18
【问题描述】:

这是一个科学项目,几个月后到期。我是一个完整的初学者,我真的不知道这个简单的凯撒密码程序有什么问题。我使用 ascii 将字符转换为数字,向其中添加一个设定的数字,然后返回字母并为字符串中的每个重复。当我输入两个集合输入时它工作正常,但是当我使用文本框收集输入时,它给了我什至不包含在 ascii 表中的奇怪符号。

var messages = document.getElementById("messages");
var shfBox = document.getElementById("shfBox");
var strBox = document.getElementById("strBox");
var button = document.getElementById("button");

button.addEventListener("click", function() {
  var orgstr = strBox.value;
  var orgshf = shfBox.value;
  var str = orgstr;
  var shf = orgshf;
  var output = "";
  for (var i = 0; i < str.length; i++) {
    var asciiValue = str[i].charCodeAt();
    if (asciiValue >= 65 && asciiValue <= 77) {
      output += String.fromCharCode(asciiValue + shf);
    } else if (asciiValue >= 78 && asciiValue <= 90) {
      output += String.fromCharCode(asciiValue - shf);
    } else if (asciiValue >= 97 && asciiValue <= 109) {
      output += String.fromCharCode(asciiValue + shf)
    } else if (asciiValue >= 110 && asciiValue <= 122) {
      output += String.fromCharCode(asciiValue - shf)
    } else {
      output += str[i];
    }
  }

  document.getElementById("output").innerHTML = output;
  return output;
  return str;
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <ul id="messages"></ul>
  <div>
    <input id="strBox" type="text" style="padding: 10px;">
  </div>
  <div>
    <p></p>
  </div>
  <input id="shfBox" type="number" style="padding: 10px;">
  <div>
    <p></p>
  </div>
  <div>
    <button id="button" type="button" style="padding: 4px;">Submit</button>
  </div>
  <hr>
  <p id="output"></p>
  <script src="script.js"></script>
</body>

</html>

【问题讨论】:

  • 我已将您链接中的 JavaScript 添加到问题中。

标签: javascript ascii caesar-cipher


【解决方案1】:

主要问题是您在output += ... 中的加法是在进行字符串连接,而不是数字加法,因为orgshf 是一个字符串。只需替换:

var orgshf = shfBox.value;

与

var orgshf = +shfBox.value;

而且它立即工作得更好,因为这里的 + 运算符将值转换为数字。

(你也可以这样做:

var orgshf = Number(shfBox.value);

这与上述完全相同,并且由于更明确而受到许多人的青睐。正如我所说,两者都做同样的事情,这取决于个人喜好 - 选择。)

但它仍然不完美,因为有时您的字符代码会给您非字母字符。您还需要更改if 语句中的范围,以便它们依赖于orgshf。但我希望这足以让你修复它,因为主要问题是你没有像你想象的那样添加数字。

【讨论】:

    猜你喜欢
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2016-07-26
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多