Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...