我正在尝试通过Visual Studio 2013中的.html文件学习JavaScript。
我知道在JavaScript中有更简单的方法来反转字符串,但我的主要目的是理解html和JavaScript之间的交互以提供这样的解决方案。
此外,IDE必须是Visual Studio,因为我最终想使用.aspx文件对相同的逻辑进行编码。
因此,对于我最初的学习尝试,我正在尝试实现以下逻辑:
我编写的代码如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<script type="text/javascript">
function reverseString() {
var s = document.getElementById('reverseString').value;
var reversed;
for (var i = s.length - 1; i >= 0; i--) {
reversed += s[i];
}
document.getElementById('reverseString').disabled = true;
document.getElementById('reverseString').value = reversed;
}
function submit(form) {
reverseString();
}
</script>
<title>Play with Code</title>
</head>
<body>
<form name="myform" onsubmit="submit();">
Reverse String: <input type="text" id="reverseString"/><br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
它不起作用,我对如何解决它真的很无能为力。
我尝试按照这些链接提供的说明进行调试失败:
How to debug (only) JavaScript in Visual Studio?
请帮我修复此代码,如果可能的话,请告知或指导我如何调试这样的代码。
感谢。
答案 0 :(得分:1)
这是一个带有注释的工作代码,可以解释你做错了什么:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>Play with Code</title>
</head>
<body>
<form name="myform" id="form">
Reverse String: <input type="text" id="reverseString"/><br/>
<input type="submit" value="Submit"/>
</form>
<script>
function reverseString() {
var s = document.getElementById('reverseString').value;
// reverse should initialized as a empty String
// to prevent adding char to "undefined" string
var reversed = '';
for (var i = s.length - 1; i >= 0; i--) {
reversed += s[i];
}
document.getElementById('reverseString').disabled = true;
document.getElementById('reverseString').value = reversed;
}
function submit(ev) {
// preventDefault prevent the form to do his automatic
// behavior which submit the form with a new HTTP request
ev.preventDefault();
reverseString();
}
// Attach the event to the form
document.getElementById('form').addEventListener('submit', submit);
</script>
</body>
</html>
答案 1 :(得分:0)
//HTML
Reverse String: <input type="text" id="reverseString"/><br/>
<input type="button" value="Submit" onClick="funcreverse()"/>
//Script
function funcreverse () {
var s = document.getElementById('reverseString').value;
var reversed = '';
for (var i = s.length - 1; i >= 0; i--) {
reversed += s[i];
}
document.getElementById('reverseString').disabled = true;
document.getElementById('reverseString').value = reversed;
};