javascript - 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。
解决方案
代码有几个问题:
output.join('') = document.getElementById("box2")
会抛出错误。你应该设置.value
为output.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>
推荐阅读
- javascript - 是否可以使用 Javascript 从另一个网页更改一个网页?
- java - Spring JPA OneToOne 映射实体在事务测试中行为不正确
- c# - 为什么 ArrayPool 上的分配比 Stack 上的分配更快?
- c# - Asp.net Web 引用 .net 标准 2.0 库引发运行时异常
- html - Ruby on Rails 无法正确显示 CSS 级联优先级
- java - 如何将包含双精度值的字符数组转换为双精度变量,而不产生字符串对象的开销?
- google-chrome-extension - 将“所有语言环境”屏幕截图放在特定于语言环境的屏幕截图之前
- python - 发生异常:ValueError 所有输入数组必须具有相同的维数
- web-deployment - 无法访问部署到 Azure 服务结构的 Web 应用程序
- javascript - NATIVESCRIPT - 核心 (JS) - 在 TabView 和 BLANK 页面之间切换