将项目放入数组中

时间:2016-04-27 16:33:46

标签: javascript html

当我添加一个将在表格中显示的actor时,我试图将数组中的actor显示到表中。对于每个演员,我应该能够更新和删除它们。

我不确定如何从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>

1 个答案:

答案 0 :(得分:1)

如果您可以重新渲染整个表格,那么我相信您的点击事件处理程序可以只是

document.getElementById("submit").onclick = function() {
  var fName = document.getElementById("fname").value;
  Info.push({firstName: fName});
  displayActors(Info);
};

关于您的问题,Array#push正是您可以如何向数组添加新值,而value属性正是​​您从表单元素中读取值的方式。