触发声音onClick

时间:2020-02-06 19:40:04

标签: javascript html css

我一直在尝试在自己创建的游戏中添加火箭般的声音,但是我不确定如何在onClick回调中触发声音,因此每次按此按钮拍摄时都会播放一条船。

这是我的代码:

console.log(JSON.stringify(gameBoard));
// set event listener for all elements in gameboard, run fireTorpedo function when square is clicked
gameBoardContainer.addEventListener('click', fireTorpedo, false);

// initial code via http://www.kirupa.com/html5/handling_events_for_many_elements.htm:
function fireTorpedo(e) {
    // if item clicked (e.target) is not the parent element on which the event listener was set (e.currentTarget)

    if (e.target !== e.currentTarget) {
        // extract row and column # from the HTML element's id
        const row = e.target.id.substring(1, 2);
        const col = e.target.id.substring(2, 3);
        //alert("Clicked on row " + row + ", col " + col);

        // if player clicks a square with no ship, change the color and change square's value
        if (gameBoard[row][col] === 0) {
            e.target.style.background = '#bbb';
            // set this square's value to 3 to indicate that they fired and missed
            gameBoard[row][col] = 7;
            totalClicks++;
            addClick();
            console.log(totalClicks);

        // if player clicks a square with a ship, change the color and change square's value
        } else if (gameBoard[row][col] === 1 ||
            gameBoard[row][col] === 2 || gameBoard[row][col] === 3 || gameBoard[row][col] === 4 || gameBoard[row][col] === 5) {
            e.target.style.background = 'red';
            // set this square's value to 2 to indicate the ship has been hit
            gameBoard[row][col] = 8;

            // increment hitCount each time a ship is hit
            hitCount++;
            totalClicks++;
        }
    }
}

}

0 个答案:

没有答案