Here’s the order in which that code runs:
-
The variables
indexandmyProductare created and given the initial valueundefined. -
$('.product img')is used to look up elements and thenclickis used to assign an event handler to them. -
'product'+ (index + 1)+'.php'is assigned tomyProduct; note thatindexis stillundefined. Since you use it in a math expression ((index + 1)), it’s coerced to a number, which isNaNbecauseundefinedhas 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
indexis 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?