Domanda

I have this piece of code in my javascript file (I'm working with YUI):

var levels = [2, 3, 4, 5, 6, 7, 8, 9];

for(var i = 0; i < levels.length; i++) {
var level = levels[i];
    Y.all(".level"+level).get('parentNode').addClass("category_level"+level);  
};

Now, if I have this right in the end of my javascript file, it works fine. However if I have this ahead of other code, none of my other code (functions) work anymore.

I have further isolated the problem to this piece of code: .get('parentNode') - When I take that bit out, all the other code and functions work again.

I am not sure, but I think that I might have to something along the lines of:

var nodes = Y.all(".level"+level);

nodes.each(function(node){  ...
    node.get('parentNode').......

but I am struggling getting this applied to my piece of code at the top.

Thanks!

UPDATE

This piece of code is not valid for some reason:

var levels = [2, 3, 4, 5, 6, 7, 8, 9];

for(var i = 0; i < levels.length; i++) {
   var level = levels[i];
   Y.all(".level"+level).get('parentNode').addClass("category_level"+level);  
};

When I paste this into http://www.jslint.com/ it is so wrong that it cannot even scan it! "JavaScript syntax error and cannot continue to reliably parse the program"

What is so wrong with this piece of code? It says to "Move 'var' declarations to the top of the function" - but when I do that it just says the same thing again.

Is there perhaps anybody that can tell me what is wrong with that piece of code. Or is it perhaps too difficult or sthing and should be done in an easier way?

Thanks!

È stato utile?

Soluzione

I'm not sure what your HTML looks like, but if you're trying to add a class name to each level, I would use Y.each and Y.one like so:

var levels = [2, 3, 4, 5, 6, 7, 8, 9];

Y.each(levels, function (level) {
    var node = Y.one(".level"+level);
    if(node) {
        node.get('parentNode').addClass('category_level' + level);
    }
});

This would pass in a linter as well as not fail if Y.one('.level199') does not exist.

This will work for multiple level nodes:

var levels = [2, 3, 4, 5, 6, 7, 8, 9];

Y.each(levels, function (level) {
    Y.all(".level"+level).each(function (node) {
        node.get('parentNode').addClass('category_level' + level);
    });
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top