简体   繁体   中英

Get an attribute from a grid of items

I have a game board 8x8. below is the code to create the board...

for (var i = 0 ; i < TOTAL_ROWS ; i++) {
tab_imgs[i] = [];
for (var j = 0 ; j < TOTAL_COLUMNS ; j++) {
  var num_img = Math.ceil(Math.random() * NUM_IMGS);

  if (i > 1) {
    while(tab_imgs[i-2][j] == num_img && tab_imgs[i-1][j] == num_img){
      num_img = Math.ceil(Math.random() * NUM_IMGS);
    }
  }
  if (j > 1) {
    while(tab_imgs[i][j-2] == num_img && tab_imgs[i][j-1] == num_img){
      num_img = Math.ceil(Math.random() * NUM_IMGS);

      if (i > 1) {
        while(tab_imgs[i-2][j] == num_img && tab_imgs[i-1][j] == num_img){
          num_img = Math.ceil(Math.random() * NUM_IMGS);
        }
      }

    }
  }

  tab_imgs[i][j] = num_img;
  render_table += '<div class="jewel jewel_' + num_img + '" data-row="' + i + '" data-col="' + j + '" data-jewel="' + num_img + '" style="top: ' + Number(i*TOTAL_IMGS) + 'px; left: ' + Number(j*TOTAL_IMGS) + 'px;"></div>';
}
}

The code above will produce a random board. My issue is when the user resumes an existing game. I need to loop through the ALREADY produced html and grab the attribute "data-jewel" so instead of these lines:

num_img = Math.ceil(Math.random() * NUM_IMGS);

I have:

num_img = attribute('data-jewel') 

for each grid;

您可以使用jQuery .data()方法检索数据属性的值:

num_img = +$('.selector').data( 'jewel' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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