试图将img附加到表的不同部分

Trying to append a img to different parts of a table

本文关键字:同部 img      更新时间:2023-09-26

这是我的HTML,它创建了一个板,每个单元格在单击时调用我的JavaScript函数,创建一个图像。目前,图像是在主体中创建的,并且在表下可见。我希望这样,当你点击一个单元格时,图像就会在该单元格中创建。

 <pre><div id="board">
   <table>
   <th colspan="3">Infinite Tic-Tac-Toe!</th>
     <tr id="row1">
       <td class="square" onclick="add_X();">
       </td>
       <td class="square v" onclick="add_X();">
       </td>
       <td class="square" onclick="add_X();"></td>
      </tr>
      <tr id="row2">
       <td class="square h" onclick="add_X();"></td>
       <td class="square v h" onclick="add_X();"></td>
       <td class="square h" onclick="add_X();"></td>
      </tr>
      <tr id="row3">
       <td class="square" onclick="add_X();"></td>
       <td class="square v" onclick="add_X();"></td>
       <td class="square" onclick="add_X();"></td>
       </tr>
     </table>
      </div></code>

这是我的JavaScript,它的函数目前正在创建正文中的图像,而不是表中的图像。

function show_image(src, width, height, alt) {
  var img = document.createElement("img");
  img.src = src;
  img.width = width;
  img.height = height;
  img.alt = alt;
  // This next line will just add it to the <body> tag
  this.appendChild(img); 
};
function add_X(){
  var src = "http://bookriotcom.c.presscdn.com/wp-content/uploads/2013/07/x.png";
  show_image('http://bookriotcom.c.presscdn.com/wp-content/uploads/2013/07/x.png', 60, 60, "X")
};
function add_O(){
  var src = "http://store.hamiltonmarine.com/prodimg/BER-O.JPG";
  show_image('http://store.hamiltonmarine.com/prodimg/BER-O.JPG', 50, 50, "x")
}

我正试图在不复制他人的情况下创建自己的tic Tac Toe游戏,目前正在努力让X进入点击的方块。你可以在这里查看我迄今为止所做的工作。http://terribilis.github.io/Infinite-Tic-Tac-Toe/

function show_image(sender, src, width, height, alt) {
  var img = document.createElement("img");
  img.src = src;
  img.width = width;
  img.height = height;
  img.alt = alt;

  //document.body.appendChild(img); //DO NOT DO THIS.
  //REPLACE WITH BELLOW CODE
   $(sender).append(img);
};
function add_X(){
  var src = "http://bookriotcom.c.presscdn.com/wp-content/uploads/2013/07/x.png";
  show_image($(this),'http://bookriotcom.c.presscdn.com/wp-content/uploads/2013/07/x.png', 60, 60, "X")
};
function add_O(){
  var src = "http://store.hamiltonmarine.com/prodimg/BER-O.JPG";
  show_image($(this),'http://store.hamiltonmarine.com/prodimg/BER-O.JPG', 50, 50, "x")
}

请注意,我添加了额外的参数来获取sender,所以每次调用函数addx或addo时,你都必须传递它的sender,并在show_image函数中使用它来知道你希望你的img被附加到哪一行。