简体   繁体   English

用于JavaScript对象的jQuery选择器?

[英]JQuery selectors for JavaScript objects?

Is there a way to query JavaScript objects with JQuery selectors? 有没有一种方法可以使用JQuery选择器查询JavaScript对象?

For example, consider an array: 例如,考虑一个数组:

var users = [{id: 0, username: 'Alice'}, {id: 1, username: 'Bob'}, {id: 2, username: 'Cindy'}];

, then the following works fine: ,那么以下工作正常:

$(users).each(function (index, user) { ... });

I need to be able do something like this: 我需要能够做这样的事情:

$(users).find('[username="Bob"]').each(function(index, user){ ... });

, but I could figure out a proper selector string value. ,但我可以找出正确的选择器字符串值。 Any ideas? 有任何想法吗?

You could use Underscore to do it, in particular, findWhere() . 你可以使用下划线来做到这一点,特别是findWhere()

bobs = _.findWhere(users, { username: "Bob" });

If you must use jQuery, you could use... 如果必须使用jQuery,则可以使用...

bobs = $.grep(users, function(user) { return user.username === "Bob"; });

Or if your platforms support Array.prototype.filter() , use it in the same way you use jQuery's grep() . 或者,如果您的平台支持Array.prototype.filter()Array.prototype.filter()与使用jQuery的grep()相同的方式使用它。

Also, when iterating over something with jQuery that isn't a jQuery collection, don't use jQuery.prototype.each() , but use jQuery.each() . 另外,当使用非jQuery集合的jQuery进行迭代时,请勿使用jQuery.prototype.each() ,而应使用jQuery.each()

使用Array.prototype.filter ,一个本地javascript函数

users.filter(function(user) { return user.username === "Bob"; }) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM