1

私は Javascript が初めてで、document.getElementById を使用してアイテムの値を表示したいと考えています。私の例では、var= btsFrontEnd に出力された名前をリストしたいと思いますが、何か間違っています。どんな助けでも大歓迎です。

ありがとうございました。 私のフィドルへのリンク

var btsFrontEnd = {
     "employee-1": {
         "name": "Name One", 
         "phone": "1234567890",
         "email": "blah@blah.com"
        },

    "employee-2": {
                  "name": "Name Two", 
                  "phone": "1234567890",
                  "email": "blah@blah." 
     }
};


var btsemployees = {
    employees:[
        {
     "name": "Name One", 
     "phone": "1234567890",
     "email": "blah@blah.com"
    },
     { 
     "name": "Name Two", 
      "phone": "1234567890",
     "email": "blah@blah.com"
},
     { 
     "name": "Name Three", 
      "phone": "1234567890",
     "email": "blah@blah.com"
},
     { 
     "name": "Name Four", 
      "phone": "1234567890",
     "email": "blah@blah.com"
},
     {
     "name": "Name Five", 
      "phone": "1234567890",
     "email": "blah@blah.com"
}
]
};


//First argument is our data structure (an object or an array
//Second argument is a callback (logic we apply to our data structure)
$.each(btsFrontEnd, function (key, value) { 
console.log(key); //Prints this object's keys
console.log(value); //Prints immediate values from this object
console.log(btsFrontEnd[key]); 
console.log(value.name); 
    document.getElementById("names").innerHTML.value;// This is what I am referring to, I would like it to appear in the p id="names"

});
4

4 に答える 4

2

これがjsfiddleです:http://jsfiddle.net/Ss2kk/7/

// Put names into an array
var employeeNames = [];
$.each(btsFrontEnd, function (employeeid, employee) { //first is the key or index, second argument is the value
    // Check each element if it has name field
    if (employee.name !== undefined) {
        // Put its name into the array
        employeeNames.push(employee.name);
    }
});

// Join the array as comma seperated and put the content into `<p>` tag.
document.getElementById("names").innerHTML = employeeNames.join(",");
于 2013-07-01T19:19:50.807 に答える
0
var names = document.getElementById( 'names' );
names.innerHTML = '';

$.each( btsFrontEnd, function( key, value ) { 
    names.innerHTML += value.name + '<br>';    
});
于 2013-07-01T19:19:14.970 に答える
0

ループ内では、キーと値のパラメーターは、最初の反復で次の値を表します。

key
    "employee-1"

value 
    Object { name="Name One", phone="1234567890", email="blah@blah.com"}

はオブジェクトなのでvalue、次のように名前にアクセスできますvalue.name

于 2013-07-01T19:24:04.773 に答える