[英]How can I assign each div a coordinate value with a javascript function?
I've a function that generates div
s and appends them to a 'container' div, and it assigns each div
with a unique ID. 我有一个生成
div
并将其附加到“容器” div的函数,它为每个div
分配了唯一的ID。 I use a for loop to run the function and fill the 'container' div
, which is just wide enough so that the tiles being added create a square. 我使用for循环运行该函数并填充'container'div,该
div
足够宽,因此要添加的图块会创建一个正方形。
The following is my code to generate a div
: 以下是我生成
div
代码:
function cdiv(ele) {
var div = document.createElement("div");
div.className = 'tiles';
div.id = 'div' + id++; // det unique id and increment id value
div.addEventListener("click", clr);
div.dataset.taps = x;
div.dataset.xcoordinate = 0;
div.dataset.ycoordinate = 0;
ele.appendChild(div);
}
I use the following to contain the div
s being created: 我使用以下内容包含正在创建的
div
:
var div = document.getElementById('container');
for (i = 0; i < 100; i++) {
for (b = 0; b < 100; b++) {
cdiv(div);
}
}
Note - my 'container' div
is 5000px wide so that if each div being created is 50px wide, I will then have a square grid of div
s. 注意-我的“容器”
div
的宽度为5000px,因此,如果要创建的每个div的宽度为50px,则将有一个div
的正方形网格。
My problem is being able to assign each div a coordinate. 我的问题是能够为每个div分配一个坐标。 I need a function that I can use to pass through to the x/y coordinate
tag
s in each div being created, and give them a value depending on where the div is located in the 'grid'. 我需要一个函数,该函数可用于传递到正在创建的每个div中的x / y坐标
tag
s,并根据div在“网格”中的位置为其提供一个值。 The number of tiles is variable so please don't give a solution for just a 100 by 100 grid. 瓦片的数量是可变的,所以请不要只为100 x 100网格提供解决方案。
Not sure if I understand the question fully. 不知道我是否完全理解这个问题。
Would this work? 这行得通吗?
function cdiv(ele, xcoord, ycoord) {
var div = document.createElement("div");
div.className = 'tiles';
div.id = 'div' + id++; // det unique id and increment id value
div.addEventListener("click", clr);
div.dataset.taps = x;
div.dataset.xcoordinate = xcoord;
div.dataset.ycoordinate = ycoord;
ele.appendChild(div);
}
Then 然后
var div = document.getElementById('container');
for (i = 0; i < 100; i++) {
for (b = 0; b < 100; b++) {
cdiv(div, i, b);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.