[Solved] How can I use a variable outside a function in jQuery?


Here’s the order in which that code runs:

  1. The variables index and myProduct are created and given the initial value undefined.

  2. $('.product img') is used to look up elements and then click is used to assign an event handler to them.

  3. 'product'+ (index + 1)+'.php' is assigned to myProduct; note that index is still undefined. Since you use it in a math expression ((index + 1)), it’s coerced to a number, which is NaN because undefined has no numeric equivalent. So the overall result is what you see.

  4. Possibly, at some point in the future, someone clicks one of those elements, at which time index is set to a new value. This has no effect on myProduct.

You may want to move the assignment of myProduct inside the click handler, in which case you probably don’t need index outside the handler at all:

var myProduct;
$('.product img').click(function () {
    var index = $( ".product img" ).index( this );
    myProduct="product"+ (index + 1)+'.php';
});

2

solved How can I use a variable outside a function in jQuery?