简体   繁体   中英

How to make jQuery objects from an array?

anArray = ['thing1','thing2','thing3'];
$.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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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