将项目放入数组中
Putting an item in a array
当我添加一个演员时,我正在尝试将数组中的演员显示到表中,它会显示在表中。对于每个演员,我应该能够更新和删除它们。
我不确定如何从 html 获取值以显示在表中。
var actors, i;
var Info = [
{firstName: "Jason", lastName: "Statham", birth: "July 26, 1967", gender: "Male", genre: "Action, Crime, Thriller"},
{firstName: "Mark", lastName: "Wahlberg", birth: "June 5, 1971", gender: "Male", genre: "Action, Comedy, Drama"}
];
var displayActors = function(actors) {
var str = "<table class='table'>";
str += "<tr>";
str += "<th>First Name</th><th>Last Name</th><th>Date of Birth</th><th>Gender</th><th>Genre</th>";
str += "</tr>";
for(i=0; i < actors.length; i++){
str += "<tr>";
str += "<td>" + actors[i].firstName + "</td>";
str += "<td>" + actors[i].lastName + "</td>";
str += "<td>" + actors[i].birth + "</td>";
str += "<td>" + actors[i].gender + "</td>";
str += "<td>" + actors[i].genre + "</td>";
str += "</tr>";
}
str += "</table>";
document.getElementById("actorGrid").innerHTML = str;
}
window.onload = function() {
displayActors(Info);
}
document.getElementById("submit").onclick = function() {
var fName = "";
var str = "<table class='table'>";
fName = document.getElementById("fname").value;
if(fName != "") {
str += "<tr>";
str += "<td>" + Info.push({firstName: fName}) + "</td>";
str += "</tr>";
}
str += "</table>";
document.getElementById("actorGrid").innerHTML += str;
}
<div class="main">
<h2 class="ad">Add Actors</h2>
<div id="add">
<label>First Name</label><br />
<input type="text" id="fname"/><br />
<label>Last Name</label><br />
<input type="text" id="lname"/><br />
<label>Date of Birth</label><br />
<input type="date" id="dob"/><br />
<form action="">
<label>Gender:</label><br />
Male<input type="radio" name="gender" value="Male" id="male"/>
Female<input type="radio" name="gender" value="Female" id="female"/><br />
</form>
<form action="">
<label>Genre:</label><br />
<label>Action<input type="checkbox" id="action"/></label>
<label>Adventure<input type="checkbox" id="adventure"/></label>
<label>Thriller<input type="checkbox" id="thriller"/></label>
<label>Drama<input type="checkbox" id="drama"/></label>
</form>
<br /><input type="button" id="submit" value="Add Actor" />
<hr>
</div>
<div id="actorGrid"></div>
</div>
如果您可以重新渲染整个表,那么我相信您的点击事件处理程序可以
document.getElementById("submit").onclick = function() {
var fName = document.getElementById("fname").value;
Info.push({firstName: fName});
displayActors(Info);
};
关于您的问题,Array#push
正是如何向数组添加新值,而value
属性正是您从表单元素中读取值的方式。
相关文章:
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- 按不同项目对对象数组进行排序
- 使用JavaScript或jQuery检查单选按钮选择是否与数组中的项目匹配
- JS:从整个数组中每次得到5个项目,并得到平均值
- 使用圆中的数组更改背景颜色项目
- 编辑CSV数组中的项目-快速CSV node.js
- 我可以限制我添加到数组中的项目数量吗
- 使用javascript/jquery从现有数组中创建一个新数组,该数组保存项目存在的次数
- 什么's JavaScript数组中项目的作用域
- 将项目放入数组中
- 使用 id 和 Javascript 从数组中删除项目
- (角度.js)如何通过过滤器计算数组中有多少项目
- 如何通过迭代对象数组来删除某些项目
- Lodash 从与值数组不匹配的数组中获取项目
- 发布要形成的 n 个项目的数组
- 查找数组中项目包含子字符串的索引
- 我怎么能只保留符合特定条件的数组项目
- 关于将数组项目处理为分区的问题
- Php回显数组项目逐个点击(唯一)
- 连续删除数组项目(游戏障碍)