2

https://jsfiddle.net/12xmodp9/1/

When doing each with jquery, how do I use the number selected each time?

eg. in this case I would expect the alert to display the number of the element clicked on.

<div id="foo"></div>
<script type="text/javascript">
for (i = 0; i < 20; i++) {
    $('#foo').append(
        $('<a>',
            {href: '#',
            id: "foo_" + i,
            html: i 
            }).on("click", function(){alert(i)})
    );
}
</script>

Instead it always displays "20"

wcndave
  • 306
  • 2
  • 12
  • I've read the duplicate referred to, and am none the wiser. I guessed already that it's do to with scopes and closures, however can't see why for example the id is incremented, however the function not. Marking as duplicate with another question that doesn't answer mine simply enough makes me feel stupid and doesn't help, yet I am not a beginner at this... – wcndave Oct 19 '18 at 21:42
  • I don't think this a duplicate of that question as it's possible that he didn't realize he can use the event variable passed when he created the event like the code here https://jsfiddle.net/12xmodp9/3/ – Mohammed Oct 19 '18 at 21:46
  • That could be helpful, however I wrote just example code. I really need to access the iterated i value. – wcndave Oct 22 '18 at 07:20
  • I can't post as answer, so comment it is. The easy answer is that as "i" is remembered within the scope, you have to call an external function that will create it's own version of "i" each time. I was hoping to avoid that, as a) it's more messy and b) if there are lots of values / objects / methods in the Constructor / function one is working in, you have to find a way to pass all those over. I was hoping for some sort of alert(valueAsOfNow(i)) feature. – wcndave Oct 23 '18 at 20:10

1 Answers1

0

Quick workaround is to alert your html which is "i"

    <script type="text/javascript">
for (i = 0; i < 20; i++) {
    $('#foo').append(
        $('<a>',
            {href: '#',
            id: "foo_" + i,
            html: i 
            }).on("click", function(){alert($(this).html())})
    );
}
</script>
piotrruss
  • 417
  • 3
  • 11