Reputation: 3440
I am using a plugin, which creates a navigation to a lists of sections in my html document.
I want to insert a custom name for every navigation-point, while its currently "Navigation 1", "Navigation 2", "Navigation 3". At the end it should be something like "Dogs", "Cats", "Squirrels".
The current code is:
if(settings.pagination == true) {
paginationList += "<li><a data-index='"+(i+1)+"' href='#" + (i+1) + "'><span class='icon'><img src='img/icons/icon"+(i+1)+".png' width='20' height='20' alt='icon"+(i+1)+"'></span><span class='link'>Navigation "+(i+1)+"</span></a></li>"
}
I thought about a workaround, because the menu already has the "+(i+1)+" tag to use. So I thought about creating a list of variables
var navi1 = dogs
var navi2 = cats
var navi3 = squirrels
And use these variables (as they are already numbered starting by 1 say something like
take variable "navi(i+1)"
How can I do this, as I am not a too skilled jquery developer yet?
Best regards, Marian.
Upvotes: 0
Views: 51
Reputation: 7522
If your variables are defined in global scope, you can access them via window
or this
too, like this:
window.nav1
or this.nav1
.
This will allow you to use the bracket notation to access these properties, like this:
window['nav1']
or this['nav1']
... and so you can use this notation to apply dynamic names for property names:
window['nav' + i]
or this['nav' + i]
.
UPDATE
You can use a navigation array
, then iterate over its items and create the list items. Here is the example:
var nav = [ 'dogs', 'cats', 'squirrels' ],
paginationList = '';
for (var i = 0, i < nav.length; i < l; i++) {
paginationList += '<li>';
paginationList += '<a data-index="' + (i+1) + '" href="#' + (i+1) + '">';
paginationList += '<span class="icon">';
paginationList += '<img src="img/icons/icon' + (i+1) + '.png" width="20" height="20" alt="icon' + (i+1) + '">';
paginationList += '</span>';
paginationList += '<span class="link">' + nav[i] + '</span>';
paginationList += '</a>';
paginationList += '</li>';
}
In this snippet I created a nav
array and used the for
loop to iterate over its items. Inside of loop variable i
changes its value for each iteration. So in the first iteration i
is equal to 0
, in the next one 1
and so on, until this condition become false i < nav.length
, where nav.length
is the count of items inside of nav
array.
You can fetch the value of array item using indices, like this: nav[1]
, which is the second element of the array, because indexing starts at 0
. So inside of loop you access items using i
as an index, like this: nav[i]
.
Also I have broken down your one-line code to make it more readable.
If anything is not clear, please ask me.
Upvotes: 1