计算数字ID

时间:2015-02-08 21:09:55

标签: javascript class dom

我不太确定如何在标题中说出这一点,所以,谢谢你点击这个。

现在我的问题是:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<style>
    .block {
        background-color: black;
    }
</style>
<table border='1px'>
    <tr>
        <td id='11'></td>
        <td id='12'></td>
        <td id='13'></td>
        <td id='14'></td>
        <td id='15'></td>
    </tr>
    <tr>
        <td id='21'></td>
        <td id='22'></td>
        <td id='23'></td>
        <td id='24'></td>
        <td id='25'></td>
    </tr>
    <tr>
        <td id='31'></td>
        <td id='32'></td>
        <td id='33' class="block"></td>
        <td id='34'></td>
        <td id='35'></td>
    </tr>
    <tr>
        <td id='41'></td>
        <td id='42'></td>
        <td id='43'></td>
        <td id='44'></td>
        <td id='45'></td>
    </tr>
    <tr>
        <td id='51'></td>
        <td id='52'></td>
        <td id='53'></td>
        <td id='54'></td>
        <td id='55'></td>
    </tr>
</table>
<button onclick="blockUp()">Up</button>
<button onclick="blockDown()">Down</button>
<button onclick="blockLeft()">Left</button>
<button onclick="blockRight()">Right</button>
<script>
var blockUp = function() {
    var oldBlock = document.getElementsByClassName("block")[0].id;
    var newBlock = Math.floor(oldBlock + 1);
    document.getElementById(newBlock).classList.add("block");
    document.getElementById(oldBlock).classList.remove("block");
}

    
</script>
</body>
</html>
此代码不完整,因为我想先解决这个问题。

我想使用Math.floor获取某个ID(因此,ID作为数字),并操纵它们。更具体地说,我想找到当前具有.block类的单元格的ID,使用Math.floor(oldBlock + 1)查找上面的单元格的ID,从原始单元格中删除该类,并添加该类到新的细胞。我使用了变量,以便函数始终能够运行,而不是生成一百万if / else if / else语句。

不幸的是,这不适用于我当前的代码。我怎么能这样做?

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

你必须确保“oldBlock”在尝试使用它之前包含一个数字(比如添加1):

var oldBlock = +document.getElementsByClassName("block")[0].id;

这是一种做法。您也可以使用parseInt()

var oldBlock = parseInt(document.getElementsByClassName("block")[0].id, 10);

“id”属性的值将是一个字符串,因此如果您在添加操作中涉及该值,JavaScript会将其视为字符串连接。通过强制它成为第一个数字,你将获得你想要的效果。