我正在尝试使用javascript创建一个简单的电话簿。我希望当用户单击“添加联系人”时,其姓名和电话出现在底部的单独分区中。 我有下面的代码,但由于某种原因它无法正常工作。你有什么想法?
var persons = {};
function showTable() {
str = "";
for (var i = 0; i < persons.length; i++) {
str += `<tr>
<td>${persons[i].name}</td>
<td>${persons[i].phone}</td>
</tr>`
}
document.querySelector("table tbody").innerHTML = str;
}
<!DOCTYPE html>
<html>
<head>
<title>PhoneBook</title>
</head>
<body>
<h1>PhoneBook</h1>
<form>
<label for="name">Name</label>
<input type="text" name="name" id="name">
<label for="phone">Phone</label>
<input type="text" name="phone" id="phone">
<input type="button" class="btn" value="Add contact" onclick="showTable;">
</form>
<div id="containerPhoneBook">
<table id="inputs">
<thead>
<tr>
<td>Name</td>
<td>Phone</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
答案 0 :(得分:1)
df.write.format("parquet").path("/some/path")
,并且可以预先填充它。预填充的数组看起来像[]
var persons = [{ name:"Fred", phone:" 123"}, {name:"Bob", phone:"234"}];
一样使用()调用函数
showTable()
var persons = [];
function showTable() {
str = "";
for (var i = 0; i < persons.length; i++) {
str += `<tr>
<td>${persons[i].name}</td>
<td>${persons[i].phone}</td>
</tr>`
}
document.querySelector("table tbody").innerHTML = str;
}
function addTable() {
persons.push({
name: document.getElementById("name").value,
phone: document.getElementById("phone").value
})
showTable();
}
window.addEventListener("load", showTable);
您看到我使用事件处理程序来等待表存在。
不建议使用内联事件处理程序,因此您也可以这样做
<!DOCTYPE html>
<html>
<head>
<title>PhoneBook</title>
</head>
<body>
<h1>PhoneBook</h1>
<form>
<label for="name">Name</label>
<input type="text" name="name" id="name">
<label for="phone">Phone</label>
<input type="text" name="phone" id="phone">
<input type="button" class="btn" value="Add contact" onclick="addTable();">
</form>
<div id="containerPhoneBook">
<table id="inputs">
<thead>
<tr>
<td>Name</td>
<td>Phone</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
答案 1 :(得分:0)
您必须在persons
后面添加新人员。为此,我创建了一个新函数addPerson
。
JS
var persons = [];
function addPerson(name,phone){
person={
name:name.substring(0),
phone:phone.substring(0)
}
persons.push(person)
showTable()
}
function showTable() {
str = "";
for (person of persons) {
str += '<tr>
<td>'+person.name+'</td>
<td>'+person.phone+'</td>
</tr>'
}
document.querySelector("table tbody").innerHTML = str;
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>PhoneBook</title>
</head>
<body>
<h1>PhoneBook</h1>
<form>
<label for="name">Name</label>
<input type="text" name="name" id="name">
<label for="phone">Phone</label>
<input type="text" name="phone" id="phone">
<input type="button" class="btn" value="Add contact" onclick="addPerson(document.getElementById('name').value,document.getElementById('phone').value)">
</form>
<div id="containerPhoneBook">
<table id="inputs">
<thead>
<tr>
<td>Name</td>
<td>Phone</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>