Javascript 如何通过用户输入更改文本?
我有一个包含Javascript 如何通过用户输入更改文本?,javascript,jquery,Javascript,Jquery,我有一个包含和的页面 我不知道如何做,用户在输入中写入的文本将显示为跨度 代码(无法正常工作): HTML: <h1>Lets talk with SpongBob!</h1> <span>Say "hello":</span> <form name="frm"><input name="question" type="text"><input id="submit" type="submit" value="Sub
和
的页面
我不知道如何做,用户在输入中写入的文本将显示为跨度
代码(无法正常工作):
HTML:
<h1>Lets talk with SpongBob!</h1>
<span>Say "hello":</span>
<form name="frm"><input name="question" type="text"><input id="submit" type="submit" value="Submit"></form>
<div id="igool"><span id="talk"></span></div>
<div id="Triangle"></div>
<img src="http://static.tumblr.com/f1bbfdf0fd794b1cf8d243d65644be01/i0ldeup/bURmj2ccf/tumblr_static_spongebob.jpg"/>
body {
font-family: "Comic Sans MS", cursive, sans-serif;
}
h1 {
text-align: center;
}
img {
width: 300px;
margin-left: 20%;
}
input {
position: absolute;
width: 10%;
margin-left: 45%;
border: 2px solid black;
border-radius: 4px;
background-color: lightgray;
}
#submit {
margin-left: 57%;
width: 5%;
}
span {
position: absolute;
margin-left: 37%;
}
#Triangle {
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 30px solid lightgray;
margin-top: -0.5%;
margin-left: 41%;
}
#igool {
width: 120px;
height: 100px;
background-color: lightgray;
border-radius: 100%;
margin-left: 38%;
margin-top: 8%;
}
#talk {
margin-left: 2%;
margin-top: 3%;
}
Javascript
if (document.forms['frm'].question.value == "hello") {
document.getElementById("talk").innerHTML="Hello you to!";
}
else {
document.getElementById("talk").innerHTML="WhatEver...";
}
如果我没有弄错,您需要JavaScript事件。查找
blur()
或keyup()
这样就可以了。您需要将它们连接到输入标记。您不必实际提交表单,如果您只需要JavaScript,那么就可以使用这样的代码:
window.onload = function() {
var oForm = document.forms["frm"];
var oTalkSpan = document.getElementById("talk");
oForm.onsubmit = function() {
if (this.elements["question"].value == "hello") {
oTalkSpan.innerHTML="Hello you to!";
}
else {
oTalkSpan.innerHTML="WhatEver...";
}
return false;
};
};
如果您选择提交表单,则必须使用服务器端语言,如PHP、ASP.NET或许多其他语言,但不能使用客户端脚本。请尝试以下方法:
演示:
使用jquery只需三行即可完成以下操作:
$('input#one').keyup(function(){
$('span#test').html($(this).val());
})
和html:
<span id="test"></span>
<br/>
<input type="text" id="one"/>
这是您希望它什么时候工作?当你点击提交?
<span id="test"></span>
<br/>
<input type="text" id="one"/>