我有一个像这样的多维数组:
var squares = new Array();
for(var i = 0; i <= 8; i++)
{
squares[i] = new Array();
for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
{
if (squares[i] == null)
{
squares[i] = ''+j;
}
else
{
squares[i].push('' + j);
}
}
}
当我点击一个正方形时,我想从多维数组中获取索引:
angular.element('.click').click(function() {
var squareId = angular.element(this).attr('id'); //Rutans id
for(var k = 0; k <= 8; k++)
{
var squareIndex = squares[k].indexOf(squareId);
}
console.log(squareIndex);
但这只能通过console.log导致-1。谁可以帮助我?
答案 0 :(得分:0)
使用indexOf()只检查该数组中是否存在该ID。因此,如果它出现在第一个数组中,它将继续循环它们返回-1覆盖先前的值。
您需要做的是在找到循环时停止循环并返回k,即当前正在迭代的数组的索引。
这是一个小提琴,希望这会有所帮助 Fiddle
var squares = new Array();
for(var i = 0; i <= 8; i++)
{
squares[i] = new Array();
for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
{
if (squares[i] == null)
{
squares[i] = ''+j;
}
else
{
squares[i].push('' + j);
}
}
}
console.log(squares);
$('a').on('click', function(){
var squareId = $(this).attr('id');
var squareIndex = 0,
numberIndex = 0;
for(var k = 0; k < squares.length; k++)
{
squareIndex = squares[k].indexOf(squareId);
if (squareIndex > -1) {
numberIndex = squareIndex;
squareIndex = k;
break
}
}
alert('NumberIndex: '+ numberIndex+' ParentSquareIndex: '+ squareIndex);
});
答案 1 :(得分:0)
请看这里http://plnkr.co/edit/aldjCQRchgESR7IWn367?p=preview我希望这会有所帮助。
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.22/angular.js" data-semver="1.2.22"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello !</p>
<table>
<tr ng-repeat="lines in squares track by $index ">
<td ng-repeat="nr in lines track by $index" ng-click="getMyId(nr)">{{nr}}</td>
</tr>
</table>
</body>
</html>
<强> JS:强>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
var squares = [];
for(var i = 0; i <= 8; i++)
{
squares[i] = [];
for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
{
if (squares[i] === null)
{
squares[i] = ''+j;
}
else
{
squares[i].push('' + j);
}
}
}
$scope.squares = squares;
$scope.getMyId = function(id){
alert(id);
}
console.log(squares);
});