检查THIS是否点击了TD's的值与数组的值匹配

Check if THIS clicked TD's value matches the value of an array

本文关键字:数组 是否 THIS TD 检查      更新时间:2023-09-26

所以我正在制作一款战舰游戏,除了这一点之外,其他一切都很好。我似乎想不出你该怎么做。我想检查单击的TD的值是否与数组中的值匹配,是否确实将innerHTML更改为hit(即X)。(this)代表点击的TD。在这种情况下你能使用indexOf吗?

    function play() {
           if ((this).value == shipLocations.indexOf((this).value)) {
                (this).innerHTML = hit;
           }
       else {
          (this).innerHTML = miss;    
        }
   }

<script>
    var shipLocations = ["5"];
    function play(button) {
        if (-1 != shipLocations.indexOf((button).value)) {
            (button).innerHTML = "hit";
        }
        else {
            (button).innerHTML = "miss";
        }
    }
</script>
<button value="5" onclick="play(this)">meh</button>

假设存储了船舶位置,而不是船舶对象

我觉得你在比较苹果和桔子。indexOf返回您在shipLocations数组中查找的值的索引,而不是存储在数组中的船只的实际位置。

更新

fiddle显示,您也以错误的方式访问属性。以下是正确的方式:

if (parseInt((this).getAttribute("value")) == shipLocations[shipLocations.indexOf(parseInt(this.getAttribute("value")))]) {
        (this).innerHTML = hit;
}

this指的是html元素,而不是javascript对象,您可以使用.来访问属性。使用getAttribute("value")工作。

旁注:船只有时会被放置在"接触"的位置。我认为这是违法的;-)