简体   繁体   English

通过使用数组获取随机div的ID

[英]Get ID of a random div by using an array

I'm trying to create a right-click function with just JavaScript, so I thought I would use a mouseover function, eg: 我正在尝试仅使用JavaScript创建一个右键单击函数,所以我想我将使用鼠标悬停函数,例如:

mysteryDiv.onmouseover=function(){
    if (rightMBclicked === true)
    {
    console.log(mysteryDiv.id);
    }
}

The problem is, I can't figure out how to get 'mysteryDiv', here is the function that creates the blocks (I need to access them), and a few important variables: 问题是,我不知道如何获取“ mysteryDiv”,这是创建块的函数(我需要访问它们),以及一些重要的变量:

var blocknum = 0;
var blockmax = 2500;
var blocks = [];

function createBlocks()
    {
    if (blocknum < blockmax)
    {
    blocknum += 1;
    var block = document.createElement("div");
    block.className = "block"; 
    block.id = "block" + blocknum;
    blocks.push(blocknum);
    block.style.width = block_width + "px";
    block.style.height = block_height + "px";
    block.style.cssFloat = "left";
    //block.style.backgroundColor = "#228B22";
    block.style.backgroundImage="url('textures/grass.jpg')";
    document.getElementById("container").appendChild(block,container.firstChild);
    createBlocks();
    }
    else
    {
    if (blocknum === blockmax)
    {
    createPlayer();
    paused = false;
    }
    }
    }

EDIT: 编辑:

I'm trying to get the ID of the block (mysteryDiv) that my mouse cursor is over. 我正在尝试获取鼠标光标移到的块(mysteryDiv)的ID。

I assume you want to handle event for dynamically created your blocks. 我假设您要处理动态创建的块的事件。 Please try this ... hope this is what you want ... I am not sure what is rightMBclicked ... for the testing case set it to true 请尝试这个...希望这就是您想要的...我不确定是rightMBclicked ...对于测试用例,将其设置为true

//after this line
block.style.backgroundImage="url('textures/grass.jpg')"; 

//here
block.onmouseover = function(e){

    if (rightMBclicked === true)
    {
        console.log(e);
        console.log(this.id);
    }
};

//before this line
document.getElementById("container").appendChild(block,container.firstChild);

At first sight, you might need to bind the same event handler to all of your divs. 乍一看,您可能需要将相同的事件处理程序绑定到所有div。

Something like this: 像这样:

handlerFunction = function(e)
{
        console.log(e)

}

divElements = document.getElementsByTagName("div")

for (i in divElements)
    divElements[i].onmouseover = handlerFunction

Of course, maybe you will run into trouble with bubbleling. 当然,也许您会遇到冒泡的麻烦。 You might want to be more specific on how your html is structured, so we can be more helpful. 您可能想更详细地说明html的结构,以便我们提供更多帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM