需要用图像代替innerText进行交叉和交叉

时间:2019-02-12 11:54:07

标签: javascript html css

我不需要在“交叉点”网格中显示“ O”或“ X”,而是需要它显示不交叉点的图像。 JavaScript中的innerText可以做到这一点,但是我想替换掉它,以便在网格中显示我的png文件。我该怎么办?

这是我在大学里做的作业,我的老师给我们设置了将文本更改为网格内图像的任务,但我被困住了。我尝试将其更改为“ innerHTML”并使用img src,但感觉好像丢失了一些东西。

var currentPlayer = "O";
var won = false;

alert("Welcome to the game!")

function place(box) {
    if(box.innerText != "" || won) return;
    box.innerText = currentPlayer;
    currentPlayer == "O" ? currentPlayer = "X" : currentPlayer = "O";
    checkGameBoard();       
}

function checkGameBoard() {
    for(var i = 0; i <= 2; i++) {
        checkWinner(document.getElementById(i + "_0").innerText,
        document.getElementById(i + "_1").innerText,
        document.getElementById(i + "_2").innerText);
    checkWinner(document.getElementById("0_" + i).innerText,
        document.getElementById("1_" + i).innerText,
        document.getElementById("2_" + i).innerText);
 }
 checkWinner(document.getElementById("0_0").innerText,
       document.getElementById("1_1").innerText,
       document.getElementById("2_2").innerText);
 checkWinner(document.getElementById("0_2").innerText,
       document.getElementById("1_1").innerText,
       document.getElementById("2_0").innerText);
 }

function checkWinner(first, second, third) {
    if(first != "" && first == second && first == third) {
        alert("Winner! Well done!");
        won = true;
 }

}

我期望网格中的是png图像,而不是网格中的“ X”和“ O”。

2 个答案:

答案 0 :(得分:1)

首先,您需要创建一个img html标签并将其附加到DOM上,如下所示

const image = document.createElement("img").src = "your image source";
box.innerHTML = ""; // remove any text from the box
box.append(image); // add the image inside of your element  

答案 1 :(得分:1)

以这个为例:

var img = new Image(100,100);  // (width = 100, height = 100)  are optional 
img.src = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSxjnfF8reo6uB7p6b98J0eEsJvbRtumlTtKcV_6qfxHm58O5ApnQ';
var box = document.getElementById('box');
box.appendChild(img);
<div id="box"></div>