开发者

How to make jQuery objects from an array?

anArray = ['thing1','thing2','thi开发者_开发知识库ng3'];
$.each(anArray, function (i,el) {
   var object = 'name.space.' + el;
   var selector = 'node-' + el;
   var object = $('#' + selector);//need object here to be interpreted as it's value
       //as if: var name.space.thing1 = $('#' + selector);
});

such that these are usable jQuery objects:

console.log(name.space.thing1);
console.log(name.space.thing2);
console.log(name.space.thing3);

I feel like eval() is involved. I'm hydrating navigation selectors so as pages are added/removed, we just update the array. We could build the array from the nav nodes, but either way, we still need to be able to make these namespaced selectors...


You will have to use bracket notation:

var array = ['thing1', 'thing2'];
var object = {};
object.space = {};
$.each(array, function () {
    object.space[this] = $('#node-' + this);
});

console.log(object.space.thing1); // [<div id="node-1">]; 


I am not sure what are you trying to accomplish, but

name.space[el] = $('#' + selector);

might work.

Object properties are always accessible with the bracket notation as well. This means that obj.xy is just the same as obj['xy'], but the latter is more flexible and can be used in situations like yours.


var anArray = ['thing1','thing2','thing3'];
var name    = {space:new Array()};

$.each(anArray, function (i,el) {
   var selector = 'node-' + el;
   name.space[el] = $('#' + selector);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜