1

I'm not that experienced in javascript and totally new to the whole loop idea but I know it can save a lot of code. So I have been trying to create a loop. This is my problem: I find every variable in the first line and want to add a value to the A. I know $(this) doesn't do the trick but I can't come up with something better what works.

Basically, I want for the first variable amount[0] and for the second amount[1] and so on..

This is what I have so far..

$(a).each(function() {
    $(this).find("a").after( (" (" + amount[0] + ")"));
});
2
  • $(this) represents anchor so you can add do it directly Commented Aug 31, 2015 at 8:07
  • I know this is not really working in this case, since it goes to every variable. Commented Aug 31, 2015 at 8:10

2 Answers 2

2

So I assume you want somthing like this:

$('a').each(function(index) {
    if (index >= amount.length) return; // avoind IndexOutOfBounds Exception
    $(this).after( " (" + amount[index] + ")"); // $(this) will refer to a link, in this each
});

After each link (a) you want to add a '(text_from_amount)' where text_from_amount is taken from amount array?

More about each, can be found here.

Sign up to request clarification or add additional context in comments.

Comments

1

First of all, you're using jQuery, not native Javascript.

The $(selector).each function may take two parameters: The first one is the loop counter and the second one is the callback.

(Use the counter of the each() method, assuming that the amount array has all those entries. The better aproach would be to use a conditional to check if amount[counter] exists)

$(a).each(function(counter, value) {
    //conditional to check array entry
    if (amount[counter] !== undefined) {
        $(value).find("a").after('(' + amount[counter] + ')');
    }
});

The $.each() function (without selector) may be used to iterate over arrays or an array of objects:

// An array
var myArray = ['one', 'two', 'three'];
$.each(myArray, function (counter, value) {
    console.log(counter);
    console.log(value);
});

// An array of objects
var myArrayObject = [
    {
        one: 'foo',
        two: 'bar'
     },
     {
        one: 'another foo',
        two: 'another bar'
     }
 ];
$.each(myArrayObject, function (counter, value) {
    console.log(counter);
    console.log(value.one);
    console.log(value.two);
});

See the docs for more information.

2 Comments

Alright, I understand. But how can I say for every "a" that he finds he adds a +1 to the amount[0]
See edited answer. Use the counter of the each method, assuming that the amount array has all those entries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.