【问题标题】:Find objects by id using arrays in js在js中使用数组按id查找对象
【发布时间】:2020-05-04 20:53:39
【问题描述】:

在我的代码中,我有一个 8x8 表,每个 <td> 的 id 为 0-7 之间的两个数字(即“0、0”、“2、5”等)。我需要的是创建一个函数,当我单击<td> 时,它会为我提供 id 的第一个和第二个数字。 我想也许我可以用数组来做到这一点,但我不知道如何从 id 中提取两个单独的数字。

我是 javascript/html 的初学者,所以带有答案的解释将非常有帮助!

【问题讨论】:

  • 请澄清:每个<td> 标签都有唯一的ID?还是内部文本包含 2 个数字?

标签: javascript html arrays html-table


【解决方案1】:

首先,你需要获取所有的<td>标签,然后循环它们并设置一个onclick函数:

var cells = document.getElementsByTagName("td");
for (let index = 0; index < cells.length; index++) {
    var cell = cells.item(index);
    cell.onclick = function (e) {
        // Do something
    }
}

onclick 函数中,您有包含目标html 元素(&lt;td&gt;)的点击事件,现在我们只需要提取数字:

var text = e.target.innerText;                
var result = text.split(","); // splited as text not number
var n1, n2;
n1 = Number(result[0]); // casting text to int(number)
n2 = Number(result[1]); // casting text to int(number)

其中n1n2 是提取的数字。

这里是完整的代码:

var cells = document.getElementsByTagName("td");
for (let index = 0; index < cells.length; index++) {
    var cell = cells.item(index);
    cell.onclick = function (e) {
        var text = e.target.innerText;                
        var result = text.split(",");
        var n1, n2;
        n1 = Number(result[0]);
        n2 = Number(result[1]);
    }
}

【讨论】:

    【解决方案2】:

    根据 W3:

    id 值必须至少包含一个字符,并且必须包含空格(空格、制表符等)。

    所以如果你是通过&lt;td id="yourId"&gt;设置id,那么yourId就不能是0, 0

    要解决该问题,您可以使用 ID 为 xy,其中您的两个数字是 xy,假设它们的范围是 0 到 7。

    <td onclick="clicked(event)" id="25">click me</td>
    

    然后就可以得到id的第一个和第二个字符了。

    function clicked(event) {
      const id = event.target.id;
      const x = parseInt(id.charAt(0));
      const y = parseInt(id.charAt(1));
      console.log(x);
      // 2
      console.log(y);
      // 5
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-18
      相关资源
      最近更新 更多