Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

javascript - How can I use a variable outside a function in jQuery?

I am trying to return, using .index method, the position of the picture I am clicking on and then use that number in another variable that has to be external to the function.

var index;
    $('.product img').click(function () {
        index = $( ".product img" ).index( this );  //it returns an integer, as expected             
        })

var  myProduct = 'product'+ (index + 1)+'.php'; // it returns productNaN.php

Only that, although the index method works properly, in my second variable I get instead of an integer NaN.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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';
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...