首页 > 解决方案 > 更改AngularJS中的背景图像按钮

问题描述

309/5000 你好,这是我的第一篇文章。我正在用 AngularJS 开发一个残酷的井字游戏。但是当我单击它时,我无法更改按钮的图像。游戏还没有结束,我只需要这件事的帮助。对不起英文“MACCHERONICO”(意大利面)。谢谢你们。

app.controller('gameController', function ($scope, $routeParams) {
$scope.p1name = $routeParams.p1name;
$scope.p2name = $routeParams.p2name;
$scope.griglia = ['', '', '', '', '', '', '', '', ''];
$scope.player = $scope.p1name;
$scope.turno = 0;
var img_array = ['imm\broccolo-sorridente-alimenti-verdure-1138234.png',
    'imm\pomodoro-sorridente-alimenti-verdure-1130307.png'];
$scope.img;
$scope.riempi = function (a) {
    console.log("entrati in riempi casella " + a);
    if ($scope.turno == 0) {
        $scope.griglia[a - 1] = "x";
    } else {
        $scope.griglia[a - 1] = "o";
    }
    $scope.aggiornaimg();
    $scope.cambiaturno();
};

$scope.cambiaturno = function () {
    console.log("entrati in cambiaturno");
    if ($scope.turno == 0) {
        $scope.turno = 1;
        $scope.player = $scope.p1name;
    } else {
        $scope.turno = 0;
        $scope.player = $scope.p2name;
    }
};
$scope.aggiornaimg = function () {
    console.log("entrati in aggiornaimg");
    for (let index = 0; index < 9; index++) {
        if ($scope.griglia[index] == "x") {
            console.log("entrati in aggiornaimg primo if");       
            document.getElementById("i" + index + 1).currentSrc = img_array[0];
        } else if ($scope.griglia[index] == "o") {
            document.getElementById("i" + index + 1).currentSrc = img_array[1];
        }
    }
};

我的 HTML

        <table >
                    <button type="button" ng-click=(riempi(1))>
                        <img ng-src="{{img}}" id="i1">
                    </button>
                </td>
                <td>
                    <button type="button" ng-click=(riempi(2))>
                        <img src="" id="i2"> </button>
                </td>
               ....
        </table>

标签: javascripthtmlangularjsimage

解决方案


我认为你的问题是"i" + index + 1没有得到你想要的 id:

for (let index = 0; index < 9; index++) {
    console.log("i" + index + 1);
}

欢迎来到JS之美,你需要的是:

for (let index = 0; index < 9; index++) {
    console.log("i" + (index + 1));
}

这样,总和在连接之前执行。


推荐阅读