【问题标题】:Find out next <td> id by clicking on a <td>通过单击 <td> 找出下一个 <td> id
【发布时间】:2013-03-27 03:05:42
【问题描述】:

我有一些像这样的td

<td id="first">first</td>
<td id="second">second</td>
<td id="third">third</td>
<td id="fourth">fourth</td> 

通过单击一个 td,我想找出其下两个 td 的 id。 当我点击“第一”时,我需要获取“第二”和“第三”值。

如何使用 JQuery 或 Javascript 实现这一点?

【问题讨论】:

  • 如果点击第四个呢?然后就没有下两个了。
  • 我建议从 jQuery tutorialdocumentation 开始。

标签: javascript jquery html-table


【解决方案1】:

jQuery

​​>

如果您单击最后一个单元格,这将提示“未定义”。

jsFiddle

$('td').click(function () {
    alert($(this).next().attr('id'));
});

JavaScript

这个方法有点老套,因为 .nextSibling 返回一个不包含id 属性的文本节点对象(不是节点)。它从其parentNode 中获取兄弟姐妹列表,然后我们遍历它们直到获得匹配项,下一个索引是下一个兄弟姐妹。

jsFiddle

var tds = document.getElementsByTagName('td');

for (var i = 0; i < tds.length; i++) {
    tds[i].onclick = function () {
        var siblings = this.parentNode.children;
        var i = 0;
        while (siblings[i] != this) { i++; }
        if (i < siblings.length)
            alert(siblings[i + 1].id);
    };
}

【讨论】:

    【解决方案2】:

    JQuery 有兄弟选择器和函数,您可以使用它们:

    http://api.jquery.com/next-siblings-selector/

    http://api.jquery.com/siblings/

    【讨论】:

      【解决方案3】:
      $('td').click(function(e) {
          e.preventDefault();
          var id = $(this).next().attr('id');
          if (id) alert(id);
      });
      

      【讨论】:

        【解决方案4】:

        您可以使用两次next()。您将必须检查下一个是否带来了一个元素,因为倒数第二个您不会获得第二个,最后您不会获得第一个和第二个下一个元素。

        Live Demo

        $('td').click(function () {
            first = $(this).next('td');
            second = first.next('td');
            if (first.length) alert(first.text() );
            else alert("No next");
        
            if (second.length) alert(second.text());
            else alert("No next");
        });
        

        【讨论】:

        • 两个 td 之间有隐藏的输入字段。当我使用 next() 时,它给出了输入字段的 ID。如何获取下一个 td 的 id?抱歉,我没有在我的问题中提到隐藏字段。
        • OP 中没有给出,你能解决这个问题吗?
        • Between two tds there are hidden input fields. 无效。
        猜你喜欢
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 2012-09-09
        • 1970-01-01
        • 2020-07-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多