views:

136

answers:

3

I am looking to do what the title says. As I am new to client side programming with java script all to together I do not know the "right" and "proper" way of achieveing what I need done.

I wish to use a simple javascript function

var x;
var items = {};

for (x = 0, x < 7; x++) {

    items[x] = new num;

}

$("li").addclass("items" + num);

Is this right? Am I on the right track even?

+5  A: 

I don't know what is num in your code but I suspect you want to get something like this:

$('li').each(function (i) {
    $(this).addClass('items' + i);
});

This will add a class with incrementing index to every li element. If you run $("li").addClass("items" + num) this will add the same class to all li elements.

BTW. JavaScript is case sensitive so you must write addClass instead of addclass.

RaYell
You can also use the index argument with $().each() to eliminate the counter. (http://docs.jquery.com/Core/each)
brianng
Updated my code. Thanks for finding that.
RaYell
Oh I just noticed your method... That's the JQuery way (= that also solved my problem... thank you so much!
A: 

More tampering....

and I found that if i did

for(var x = 0; x < 7; x++){
    $(".nav li").addClass("items_" + x);
}

I'm still not sure why the above didn't work...

oh well...

This will add the class to all `.nav li` elements on each iteration. To set something different on every item, you need to lopp using `$.each`
RaYell
A: 

RaYell is correct. You need to use $.each or you could use .eq(i).. i.e.

for(var x = 0; x < $(".nav li).length(); x++){ $(".nav li").eq(x).addClass("items_" + x); }

Ettiene