0

我想知道是否可以通过单击记录数组元素的数量。我在一个数组中有 100 多个元素:

var cubesmixed = []; 
var cubes;
for(var i = 0; i < 143; i++) {
    cubes = paper.rect(Math.floor(Math.random()*2000), Math.floor(Math.random()*2000), 0, 0);
    cubes.animate({ width: 25, height: 25 }, 500, "bounce");
    cubesmixed.push(cubes);
}

它们都是 svg 对象。如前所述,单击时我想获得该元素的数量。

$(this).click(function() { console.log(index of current element in cubes) });

提前致谢!

4

3 回答 3

0

不知道你的实际 HTML 是什么样子,或者你如何构建你的数组,以下是有效的(尽管很明显,需要根据你自己的特定用例进行定制):

// creating an array of 'li' elements:
var lis = $('li').map(function(){
    return this;
}).get();

// assigning a click-handler:
$('li').click(function(){
    // using Array.indexOf() to return the index of the 'this' node from the array:
    console.log(lis.indexOf(this));
});

JS 小提琴演示

并且,使用$.inArray()(对于那些不实现的浏览器Array.indexOf()):

$('li').click(function(){
    console.log($.inArray(this, lis));
});

参考:

于 2013-10-16T20:57:20.683 回答
0

试试 jQuery 的$.inArray()方法

var that = this;
$(this).click(function() { 
    var indexInArray = $.inArray(that, cubes);
    console.log(indexInArray);
});

您将获得该元素在数组中位置的基于 0 的索引,如果未找到匹配项,则为 -1。

于 2013-10-16T20:43:11.727 回答
0

每个数组都有一个length属性,该属性返回该数组中的元素数量:

 $(this).click(function() { 
        alert(cubes.length);
 });
于 2013-10-16T20:43:21.940 回答