javascript - 有没有办法可以在 JavaScript 中通过 if () 语句使用 .includes() 函数?

标签 javascript

我正在尝试在 repl.it 上编写 tic tac toe 游戏。我正在尝试编写 if (spaceowned)then 部分,但我需要找出 p 元素是否包含某些字符来确定空间是否被拥有。但是当我这样做时,它在控制台中显示, TypeError: document.getElementById(...).includes is not a function 在 tac (/code.js:4:35) 在 HTMLButtonElement.onclick (/:27:27) 我应该使用什么代码来解决这个问题? 我使用的代码是:

function tac() {
    var tac = prompt('Type the first letter of each word (e.g. If you want the top left, type tl)');
    var playerName = prompt('Are you player 1 or 2?');
    if (document.getElementById(tac).includes(' is availible')) {
        document.getElementById(tac).innerHTML = 'This space is owned by ' + playerName;
    } else {
        alert('That space is already taken!');
    }
}

最佳答案

您需要检查元素的文本,而不是元素本身。

if (document.getElementById(tac).innerText.includes(' is availible')) {
    document.getElementById(tac).innerText = 'This space is owned by ' + playerName;
}

关于javascript - 有没有办法可以在 JavaScript 中通过 if () 语句使用 .includes() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61197283/

相关文章:

Javascript:单击主体中除其中一个元素之外的任何位置

javascript - 多行刷卡器无法从 swiper.js 使用react

javascript - 一页上有多张幻灯片

javascript - DOMParser().parseFromString() 值得使用吗?

javascript - JavaScript 的 Reduce 是如何赋值的?

javascript - 显示 : none 的 CSS 不透明度过渡

javascript - 从 jqueryui 对话框更新数据 - 大小限制问题

javascript - 客户端修改JS

javascript - 为什么父元素上的 PreventDefault 会禁用以编程方式检查单击时的子复选框?

php - 动态添加的选择框未发布