admin管理员组

文章数量:1415645

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...

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...

Share Improve this question edited Sep 27, 2011 at 17:22 folktrash asked Sep 27, 2011 at 17:07 folktrashfolktrash 1861 silver badge11 bronze badges 3
  • what are you attempting to acplish? there has to be a better way. – Daniel A. White Commented Sep 27, 2011 at 17:12
  • Numbers aren't valid at the start of a javascript variable name. So your format won't work. – Daniel A. White Commented Sep 27, 2011 at 17:13
  • I want cached jQuery objects of navigation nodes in the dom. Prefer the creation of these objects to be tied to iterating across an array, or over the nav nodes themselves. – folktrash Commented Sep 27, 2011 at 17:13
Add a ment  | 

3 Answers 3

Reset to default 4

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 acplish, 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);
});

本文标签: javascriptHow to make jQuery objects from an arrayStack Overflow