我认为我的JavaScript函数无法正常工作以输出名称。
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>textbox.html</title>
<script type = "text/javascript">
//text box
function sayHi()
{
var txtName = document.getElementByID("txtName") ;
var txtOutput = document.getElementByID("txtOutput") ;
var name = txtName.value ;
txtOutput.value = "Hi there, " + name + "!" ;
}
//end HI
</script>
<link rel = "stylesheet"
type= "text/css"
href = "textBoxes.css" />
</head>
<body>
<h1>Text Box Input and Output</h1>
<form action = "">
<fieldset>
<label>Type your name</label>
<input type = "text"
id = "txtName" />
<input type = "button"
value = "click me"
onclick = "sayHi ()" />
<input type = "text"
id = "txtOutput" />
</fieldset>
</form>
</body>
</html>
/*我做错了什么,因为一旦我输入名称并单击我按钮就不会给出任何输出。我真的认为我的函数设置不正确。*/
它是getElementById,而不是getElementByID。 最后一个D不应该是大写字母。
尝试document.getElementById
,而不是document.getElementByID
(没有大写ID)
试试吧。
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>textbox.html</title>
<script type = "text/javascript">
//text box
function sayHi()
{
var txtName = document.getElementById("txtName") ;
var txtOutput = document.getElementById("txtOutput") ;
var name = txtName.value ;
txtOutput.value = "Hi there, " + name + "!" ;
}
//end HI
</script>
<link rel = "stylesheet"
type= "text/css"
href = "textBoxes.css" />
</head>
<body>
<h1>Text Box Input and Output</h1>
<form action = "">
<fieldset>
<label>Type your name</label>
<input type = "text"
id = "txtName" />
<input type = "button"
value = "click me"
onclick = "sayHi()" />
<input type = "text"
id = "txtOutput" />
</fieldset>
</form>
</body>
</html>
以下是一些更正:
- getElementByID应该是getElementById。
- 您也可以使用 oninput 而不是 onclick,但它会在您输入后立即显示。尝试删除按钮;它要快得多。
- 对于 txtOutput,请尝试使用输出而不是输入,除非您要键入输出本身。
以下是更正后的版本:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>textbox.html</title>
<script type = "text/javascript">
//text box
function sayHi()
{
var txtName = document.getElementById("txtName") ;
var txtOutput = document.getElementById("txtOutput") ;
var name = txtName.value ;
txtOutput.value = "Hi there, " + name + "!" ;
}
//end HI
</script>
<link rel = "stylesheet"
type= "text/css"
href = "textBoxes.css" />
</head>
<body>
<h1>Text Box Input and Output</h1>
<form action = "">
<fieldset>
<label>Type your name</label>
<input type = "text"
id = "txtName"
oninput = "sayHi()" />
<output type = "text"
id = "txtOutput" />
</fieldset>
</form>
</body>
</html>