Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 views
in Technique[技术] by (71.8m points)

javascript - How can I select a specific ID to do something?

I'm currently working on a project, now I'm facing a problem where I want to select specific IDs to do something.

How can I select specific IDs to get an img so a wall can be created?

As you can see, every tile has it's own unique tile id, now I want to select all the ids from tile0-0 to tile 0-12 and create an img for those unique ids.

How can I do that?


The code that creates those tiles:

function DrawMap()
{
  var X = Map.length;
  var Y = Map[0].length;

  var Output = "";
  for(var x = 0; x < X; x++)
  {
    for(var y = 0; y < Y; y++)
    {
      var _x = ((x*32)+(y*-32)+OffsetX);
      var _y = ((x*16)+(y*16)+OffsetY);

      if(Map[x][y])
        Output += '<img id="tile'+x+'-'+y+'" class="square" style="top: ' + _y + 'px; left: ' + _x + 'px;" src="/web/img/rooms/on.png" alt="Click To Remove" />';
      else
        Output += '<img id="tile'+x+'-'+y+'" class="square" style="top: ' + _y + 'px; left: ' + _x + 'px;" src="/web/img/rooms/off.png" alt="Click To Add" />';
    }
question from:https://stackoverflow.com/questions/65859347/how-can-i-select-a-specific-id-to-do-something

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can select all elements with this code:

document.querySelectorAll('[id^="tile0-"]');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...