JavaScript/HTML:如何在HTML正文中显示用户输入

JavaScript/HTML: How to display user input into html body?

本文关键字:HTML 显示 用户 正文 输入 JavaScript      更新时间:2023-09-26

这是我的HTML表单:

<label>Name:</label><input type ="text" input id="myName" /><br>
<label>Street:</label><input type="text" input id="myStreet" /><br>
<label>City:</label><input type="text" input id="myCity" /><br>
<label>State:</label> <input type="text" input id="myState" /><br>
<label>Zip:</label> <input type="text" input id="myZip" /><br>
<input type="submit" value="Submit" onclick="myAlert()">
</form>
//my myAlertFunc (from external file) 
function myAlert(){
    var person = new Person(document.getElementById('myName').value, document.getElementById("myStreet").value, document.getElementById("myCity").value, document.getElementById("myState").value, document.getElementById("myZip").value);
    alert(person.getFullAddress());
}
//and my getFullAddress proto from my Person class
Person.prototype.getFullAddress = function () {
    return ("Hi, my name is" + " " + this.name + "," + " " + "and my address is:" + " " + this.street + "," + this.city + "," + this.state + "," + this.zip);
};

现在,点击一下,myAlertFunc提醒用户输入值。如何在html正文中显示这些值?我知道我应该使用一个只有输入id的元素并使用document.getElementById();调用id,但我不知道之后要做什么。

提前感谢!

您要查找的属性是innerHTML: http://www.w3schools.com/jsref/prop_html_innerhtml.asp

所以,你的代码应该是这样的:
// alert(person.getFullAddress());
document.getElementById("resultDiv").innerHTML = person.getFullAddress();

其中"resultDiv"是您希望显示结果的元素的ID。

祝你好运!

你可以设置元素的innerHTML或它的值,如果它是一个输入