Here’s the order in which that code runs:
-
The variables
index
andmyProduct
are created and given the initial valueundefined
. -
$('.product img')
is used to look up elements and thenclick
is used to assign an event handler to them. -
'product'+ (index + 1)+'.php'
is assigned tomyProduct
; note thatindex
is stillundefined
. Since you use it in a math expression ((index + 1)
), it’s coerced to a number, which isNaN
becauseundefined
has no numeric equivalent. So the overall result is what you see. -
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 onmyProduct
.
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?