[英]Selecting javascript objects via their methods with jquery
How would I select: 我将如何选择:
object.id2 == "name1";
with jQuery (instead of looping through all of the objects and finding the one who's id2
matches "name1"
), so I could write something like: 使用jQuery(而不是遍历所有对象并找到id2
与"name1"
匹配的对象),所以我可以这样写:
$("name1");
or maybe: 或者可能:
$(object + " name1");
or possibly: 或可能:
$(object).attr('id2','name1');
您可以使用Lodash :
var namedObjects = _.find(allObjects, { id2: 'name1' });
var myObj = $('[id2="name1"]')
//myObj will be an array if there is more than one element that matches
As seen here: jQuery Selector API 如此处所示: jQuery Selector API
This might not be the best way to do it, but if you insist on doing it with jquery, this would be the way to do it: 这可能不是最好的方法,但是如果您坚持使用jquery进行操作,这将是这样做的方法:
var theArr = [{id2:"name0"},{id2:"name1"}];
var myObj = $(theArr).filter(function(){
return this.id2 === "name1";
}).get(0);
console.log(myObj); // Object {id2: "name1"}
http://jsfiddle.net/Tentonaxe/kTxkr/ http://jsfiddle.net/Tentonaxe/kTxkr/
of course, if you don't have to support IE<9, you can cut jquery out without changing much: 当然,如果您不必支持IE <9,则可以在不做太多更改的情况下将jquery删除:
var theArr = [{id2:"name0"},{id2:"name1"}];
var myObj = theArr.filter(function(obj){
return obj.id2 === "name1";
})[0];
console.log(myObj); // Object {id2: "name1"}
http://jsfiddle.net/Tentonaxe/kTxkr/1 http://jsfiddle.net/Tentonaxe/kTxkr/1
I'm not sure I completely understand your question, but if you create an object like this: 我不确定我是否完全理解您的问题,但是如果您创建这样的对象:
var foo = {id2 : "name1"};
You can use a jQuery selector like this: 您可以像这样使用jQuery选择器:
$(foo)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.