0

This isn't working like I expect it to. The .click function is not holding the data from my 2d array.

Version of Jquery. And I am working on chrome on a Nodejs server ( i don't think this has anything to do with it as this is all client side.);

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'></script>

So here is the code.

This is my 2d Test array. the first of the 'pair' is the element ID, the second for this test is what i wanted a console.log to print on button press.

var test = [ [ "add-edge", "Test" ], [ "add-node", "Test2" ] ]

I am looking through the pairs in the array like so. and setting the click events, and console.log response I need (this is for testing)

function setClickEvents() {
    for (var i = 0; i < test.length; i++) {
        console.log(test);
        $("#" + test[i][0]).click(function() {
            console.log(test[i][1])
        })
    }
}

I expect to see "Test" and "Test2 as an output, but get this error

MenuJquery.js:237 Uncaught TypeError: Cannot read property '0' of undefined
    at HTMLDivElement.<anonymous> (MenuJquery.js:237)
    at HTMLDivElement.dispatch (jquery.min.js:2)
    at HTMLDivElement.v.handle (jquery.min.js:2)

This stems from a larger problem I was facing as I want to look over a fair amount of 'pairs' and set 'toggleclass' events, however on every button I press it has the same callback function running and was not working as I expect. I think i'm missing a vital piece of information, I doubt this is some massive bug...

Peachman1997
  • 183
  • 1
  • 12
  • At the point that `console.log(test[i][1])` runs, `i` will be equal to `test.length` and out of bounds. – Taplar Aug 15 '19 at 18:39
  • @Taplar Thanks for the super speed response, I will have a read, what you say makes sense, I knew this has to be a super common problem and I was overlooking something so obvious, I didn't know how to word my question to be able to get my answer in this case! Thanks again! – Peachman1997 Aug 15 '19 at 18:45

0 Answers0