首页 > 解决方案 > JS 不会链接到 HTML 按钮

问题描述

我有一个 Rot13 JS 函数,我试图链接到一个按钮。预期的输出是,如果我输入“ABC”并按下“加密”按钮,加密文本将变为“NOP”。

该功能目前没有链接到 HTML 中的按钮,当我按下加密按钮时没有响应。我在 HTML 中包含了一个脚本标签。

编辑:加密器链接到按钮,但是它将“ABC”加密为“ABC”。

JavaScript:

function rot13() {
  var input = document.getElementById("box1").value;
  var output = [];

  for (var i = 0; i < input.length; i++) {
    var asciiNum = input[i].charCodeAt();
    if (asciiNum >= 65 && asciiNum <= 77) {
      output.push(String.fromCharCode(asciiNum + 13))
    } else if (asciiNum >= 78 && asciiNum <= 90) {
      output.push(String.fromCharCode(asciiNum - 13))
    } else {
      output.push(input[i])
    }
  }
  document.getElementById("box2").value = output.join('');
}
<div class="form">
        <input type="text" placeholder="plain text here..." name="plaintext" id="box1">
        <br>
        <button type="button" onclick="rot13()">Encrypt</button>
        <button type="button" onclick="rot13()">Decrypt</button>
        <br>
        <input type="text" placeholder="encrypted message here..." name="encryptedtext" id="box2">
      </div>

编辑:更正了 JS。

标签: javascripthtmlrot13

解决方案


代码有几个问题:

  • output.join('') = document.getElementById("box2")会抛出错误。你应该设置.valueoutput.join(''). 的左侧=应该是variable. output.join('')return 是值,它不能分配给任何东西。
  • output + input[i]什么都不做。您应该使用push()将值添加到数组。

function rot13() {
  var input = document.getElementById("box1").value;
  var output = [];

  for (var i = 0; i < input.length; i++) {
    var asciiNum = input[i].charCodeAt();
    if (asciiNum >= 65 && asciiNum <= 77) {
      output.push(String.fromCharCode(asciiNum + 13))
    } else if (asciiNum >= 78 && asciiNum <= 90) {
      output.push(String.fromCharCode(asciiNum - 13))
    } else {
      output.push(input[i])
    }
  }
  document.getElementById("box2").value = output.join('');
}
<div class="form">
        <input type="text" placeholder="plain text here..." name="plaintext" id="box1">
        <br>
        <button type="button" onclick="rot13()">Encrypt</button>
        <button type="button" onclick="rot13()">Decrypt</button>
        <br>
        <input type="text" placeholder="encrypted message here..." name="encryptedtext" id="box2">
      </div>


推荐阅读