转换器工作正常,它会查找与输入匹配的内容,如果找到,则会将其转换为新值。
我遇到的问题是我可以用document.write(userInput)输出新值;
但我不知道如何格式化或添加html和文本到输出。救命啊!
<!DOCTYPE html>
<html>
<body>
<h1>Value Converter</h1>
<input type="text" id="userInput"=>Enter the Value</input>
<button onclick="test()">Submit</button>
<script>
function test()
{
var userInput = document.getElementById("userInput").value;
if(userInput == "xxxx") {
userInput="yyyy";
}
else if(userInput == "yyyy") {
userInput="zzzz";
}
else {
userInput="Not Found";
}
document.write("<br /><br /><b> The equivalent value is: </b>") + (userInput) + ("< br /><br /><a href="/test.html"><b>Click here to Start Over</b></a>");
}
// Need to fix the "reset" to go back to restart the program
</script>
</body>
</html>
答案 0 :(得分:1)
更改
document.write("<br /><br /><b> The equivalent value is: </b>") + (userInput) + ("< br /><br /><a href="/test.html"><b>Click here to Start Over</b></a>");
对于
document.write("<br /><br /><b> The equivalent value is: </b>" + userInput + "< br /><br /><a href="/test.html"><b>Click here to Start Over</b></a>");
答案 1 :(得分:0)
您应该按照您希望的方式设置html,然后使用innerHTML或任何DOM函数/属性修改它,而不是覆盖页面或重新加载它。
<强> HTML 强>
<h1>Value Converter</h1>
<input type="text" id="userInput" placeholder="Enter a value" />
<div>
<span>The equivalent value is: </span>
<span id="output">Enter a value and submit first</span>
</div>
<button onclick="test()">Submit</button>
<强> JS 强>
function test() {
var userInput = document.getElementById("userInput").value;
var converted = "";
switch(userInput){
case "someXXX":
//Do whatever code here
converted = "yyy";
break;
case "someYYY":
//Do whatever code here
converted = "zzz";
break;
default:
//Do whatever when all else fails
converted = "Not found";
break;
}
var output = document.getElementById("output");
output.innerHTML = converted;
}
请注意,我将if语句更改为switch / case