我想知道是否可以通过点击来记录数组元素的数量。我在一个数组中有超过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) });
提前感谢!
发布于 2013-10-17 04:43:12
尝试使用jQuery的 ()** 方法
var that = this;
$(this).click(function() {
var indexInArray = $.inArray(that, cubes);
console.log(indexInArray);
});您将获得该元素在数组中的位置的基于0的索引,如果没有找到匹配的元素,则为-1。
发布于 2013-10-17 04:43:22
每个数组都有一个length属性,该属性返回该数组中的元素数:
$(this).click(function() {
alert(cubes.length);
});发布于 2013-10-17 04:57:21
在不知道您的实际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));
});并且,要使用$.inArray() (对于那些没有实现Array.indexOf()的浏览器):
$('li').click(function(){
console.log($.inArray(this, lis));
});参考文献:
https://stackoverflow.com/questions/19413448
复制相似问题