如何在jQuery中使用函数外的变量?

时间:2015-04-22 11:53:45

标签: javascript jquery

我试图使用.index方法返回我点击的图片的位置,然后在另一个必须在函数外部的变量中使用该数字。

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

只有这样,虽然索引方法正常,但在我的第二个变量中,我得到的不是整数NaN。

2 个答案:

答案 0 :(得分:3)

以下是该代码运行的顺序:

  1. 创建变量indexmyProduct,并给出初始值undefined

  2. $('.product img')用于查找元素,然后click用于为其分配事件处理程序。

  3. 'product'+ (index + 1)+'.php'已分配给myProduct;请注意index仍为undefined。由于您在数学表达式((index + 1))中使用它,因此它被强制转换为NaN,因为undefined没有数字等价物。所以整体结果就是你所看到的。

  4. 可能在未来的某个时刻,有人点击其中一个元素,此时index设置为新值。这对myProduct没有影响。

  5. 您可能希望在myProduct处理程序中移动click 的内容index所有:

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

答案 1 :(得分:2)

此代码仅在点击时评估,而下一行

var  myProduct = 'product'+ (index + 1)+'.php';

将在开始时进行评估,并且每次点击时不会进行一次评估,并且此时确定索引未定义,

当点击回调时,只调用里面的代码,如果你想评估它,那么下一行就没有了,然后把它放进去:

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