如何为从 setInterval 创建的每个 div 提供一个从 1 开始的 id



我知道这个问题可能已经回答了几次,但我似乎无法让它在我的代码中工作。对于每个愿意提供帮助的人,谢谢你。

有一个在屏幕上创建一个矩形的对象,然后我运行 setInerval 在屏幕上重新创建矩形,以便在屏幕上一个接一个地显示许多矩形。

问题:我需要给每个矩形一个 ID,我对 jquery 了解不多,如果我在 .block 上为 jquery 实现 attr,它会更改所有div 的所有 id。

我希望创建的每个新div 都有自己的 id 示例 id=block1,然后下一个div 将是 id=block2,依此类推,它们都将是类块。

var cHeight = window.innerHeight - 150; //size of block
var cWidth = window.innerWidth - 150; 
var Block = function(block) {
    this.block = document.createElement('div');
    this.block.className = 'block'; 

    document.body.appendChild(this.block);
}
Block.prototype.coordinates = function(top,left) {
    this.block.style.top =  top + 'px';
    this.block.style.left = left + 'px';
}
Block.prototype.size = function(width,height) {
    this.block.style.width = width + 'px';
    this.block.style.height = height + 'px';
}

function randomTop() {
    var i = Math.random();
    var y = (i * (cHeight - 0 + 1)) +0;
    var x = Math.floor(y);
    return x;
}
function randomLeft() {
    var i = Math.random();
    var y = (i * (cWidth - 0 + 1)) + 0;
    var x = Math.floor(y)
    return x;
}

function repeatBlocks() {
block1 = new Block();
block1.size(150,150);
block1.coordinates(randomTop(),randomLeft());
}
setInterval(repeatBlocks,1000);

见小提琴 https://jsfiddle.net/gustav1105/sb1vLs38/

你需要添加 var id = 1;

然后在 Block 函数中添加以下内容:this.block.id = "block"+id++;

var cHeight = window.innerHeight - 150; //size of block
var cWidth = window.innerWidth - 150; 
var id = 1;
var Block = function(block) {
	this.block = document.createElement('div');
	this.block.className = 'block';	
  this.block.id = "block"+id++;
	
	
	document.body.appendChild(this.block);
}
Block.prototype.coordinates = function(top,left) {
	this.block.style.top =  top + 'px';
	this.block.style.left = left + 'px';
}
Block.prototype.size = function(width,height) {
	this.block.style.width = width + 'px';
	this.block.style.height = height + 'px';
}
function randomTop() {
	var i = Math.random();
	var y = (i * (cHeight - 0 + 1)) +0;
	var x = Math.floor(y);
	return x;
}
function randomLeft() {
	var i = Math.random();
	var y = (i * (cWidth - 0 + 1)) + 0;
	var x = Math.floor(y)
	return x;
}
function repeatBlocks() {
block1 = new Block();
block1.size(150,150);
block1.coordinates(randomTop(),randomLeft());
}
setInterval(repeatBlocks,1000);
.block {
	position: absolute;
	border: 1px solid black;
}

最新更新