如何显示数组对象信息?

时间:2016-03-04 19:12:31

标签: javascript arrays dom

    <html>
<head>

<script>

var contacts =[];

function getInfo() {
    var firstName = prompt("Enter first name");
    var lastName = prompt("Enter last name");
    var emailId = prompt("Enter Email ID");
    var phoneNo = prompt("Enter Phone number");

    var person ={
        fname : firstName,
        lname : lastName,
        email : emailId,
        phone : phoneNo
    };


    contacts.push(person);  

    var currPerson = contacts[contacts.length-1]; //take last pushed object from the array

        if(currPerson.lname.toUpperCase().charAt(0)==='Z'){

        document.getElementById("mydiv").innerHTML +=currPerson.fname+" "+currPerson.lname + '<br/>';
        }



}

</script>

<body>

<button onclick="getInfo()">Get Person Info</button>
<p>----------------------------</p>
<div id="mydiv"></div>
</body>
</html>

Output

  

当我点击billa zopper时,他的详细信息(全名,电话和电子邮件)应出现在同一页面的右侧。我该如何实现这一目标?我知道DOM是一种选择。但是如何将DOM与数组元素链接起来呢?

1 个答案:

答案 0 :(得分:1)

我使用数组索引的相关性来做一个简单的例子。我觉得有必要指出,这不是我在实际应用程序中实际实现的方式。但是你问过如何让它在点击方面显示在div中,所以我们就是这样。

<button onclick="getInfo()">Get Person Info</button>
<p>----------------------------</p>
<div id="mydiv"></div>
<div id="target" style="float: right;">
</div>


var contacts =[];
function getInfo() {
    var firstName = prompt("Enter first name");
    var lastName = prompt("Enter last name");
    var emailId = prompt("Enter Email ID");
    var phoneNo = prompt("Enter Phone number");


     var person ={
        id: contacts.length,
        fname : firstName,
        lname : lastName,
        email : emailId,
        phone : phoneNo
    };

    contacts.push(person);
    var currPerson = contacts[contacts.length-1];
    if(currPerson.lname.toUpperCase().charAt(0)==='Z') {        
            document.getElementById("mydiv").innerHTML += "<span onclick='showMe(" + currPerson.id + ")'>" + currPerson.fname + " " + currPerson.lname + "</span><br/>";

    }
 }

function showMe(id) {
   var person = contacts[id];  /* currently corresponds to array index, could be a property lookup with underscore or whatever */
   target.innerHTML = "<div>" + person.fname + "</div>";
}