【发布时间】:2014-11-27 22:23:33
【问题描述】:
我是 jQuery 新手,我需要帮助, 我想使用键值显示对象数组中的一些数据。
我发现这个code 符合我的需要,但它可以显示所有数据,只显示第一个具有搜索键的数据。为了进一步解释,如果我添加另一个具有相同代码键的人搜索“PIR000”,第一个将显示在输出 div 中。
我需要显示我需要的所有数据,
谢谢
<span id="output"></span>
var Person = function(code, name) {
this.code = code;
this.name = name;
};
var people = [
new Person("ABC123", "Tooth Fairy"),
new Person("PIR000", "Jack Sparrow2"),
new Person("PIR000", "Jack Sparrow3"),
new Person("DEF456", "Santa Claus"),
new Person("PIR000", "Jack Sparrow"),
new Person("XYZ987", "Easter Bunny")
];
var utils = {};
// Could create a utility function to do this
utils.inArray = function(searchFor, property) {
var retVal = -1;
var self = this;
for(var index=0; index < self.length; index++){
var item = self[index];
if (item.hasOwnProperty(property)) {
if (item[property].toLowerCase() === searchFor.toLowerCase()) {
retVal = index;
return retVal;
}
}
};
return retVal;
};
// or we could create a function on the Array prototype indirectly
Array.prototype.inArray = utils.inArray;
// let's use the prototype for now
var i = people.inArray("PIR000", "code");
$('#output').text(people[i].name);
【问题讨论】: