循环槽多维数组并选择项目

时间:2018-12-15 22:42:53

标签: javascript

我想用鼠标在多维数组中选择元素,但是我做错了事,希望有人能帮助我。

我将此值添加到数组(已编辑)

xPosition.push(0);
xPosition.push(20);
xPosition.push(40);
xPosition.push(60);

row = [,];
row.push(10);
column.push(row);
row = [,];
row.push(10);
column.push(row);
row = [,];
row.push(10);
row.push(20);
row.push(30);
column.push(row);
row.push(10);
column.push(row);

id.addEventListener('mousedown', function(e) {
  var x = e.x-id.getBoundingClientRect().left;
  var y = e.y-id.getBoundingClientRect().top;
  for (var i = 0; i < column.length; i++) {
    for (var j = 1; j < column[i].length; j++) {
      if (x >= xPosition[i] && x <= xPosition[i]+10 && y >= column[j] && y <= column[j]+10) {
        alert(j);
      }
    }
  }
}, false);

1 个答案:

答案 0 :(得分:0)

您未在代码中提供更多信息。因此,希望对您有所帮助。

var column = new Array(4);

for (var i = 0; i < column.length; i++) {
 column[i] = new Array(4);
}
 xPosition = [,];
xPosition.push(0);
xPosition.push(20);
xPosition.push(40);
xPosition.push(60);

row = [,];
row.push(10);
column.push(row);
row = [,];
row.push(10);
column.push(row);
row = [,];
row.push(10);
row.push(20);
row.push(30);
column.push(row);
row.push(10);
column.push(row);

function mouseDown() {
  var x = document.getElementById('myP').getBoundingClientRect().left;
  var y =document.getElementById('myP').getBoundingClientRect().top;
  for (var i = 0; i < column.length; i++) {
    for (var j = 1; j < column[i].length; j++) {
    console.log(x,y,j);
      if (x >= xPosition[i] && x <= xPosition[i]+10 && y >= column[j] && y <= column[j]+10) {
        alert(j);
      }
    }
  }
}
<p id="myP" onmousedown="mouseDown()" >dff</p>