JavaScript / HTML:如何将用户输入显示为html正文?

时间:2013-06-18 21:13:27

标签: javascript html

继承我的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);
};

现在,onclick,myAlertFunc会警告用户输入值。如何在我的html正文中显示这些值?我知道我应该使用只有输入id的元素并使用document.getElementById();称之为id,但我不知道在那之后该怎么做。

提前致谢!

2 个答案:

答案 0 :(得分:3)

您正在寻找的属性是innerHTML:http://www.w3schools.com/jsref/prop_html_innerhtml.asp

所以,你的代码将是:

// alert(person.getFullAddress());
document.getElementById("resultDiv").innerHTML = person.getFullAddress();

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

祝你好运!

答案 1 :(得分:2)

如果是输入

,您可以设置元素的innerHTML或其值