【问题标题】:How to get parent id with jQuery?如何使用 jQuery 获取父 ID?
【发布时间】:2017-04-15 01:55:27
【问题描述】:

$('td').click(function() {
  myId = $(this).parent().attr("id");
  myItem = $(this).text();
  alert('u clicked ' + myId);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
  <tr>
    <td>Computer</td>
  </tr>
  <tr>
    <td>maths</td>
  </tr>
  <tr>
    <td>physics</td></div>
  </tr>
</table>

当我点击表格项目时,我想得到警报'u clicked science',但我得到undefined

任何帮助将不胜感激!

【问题讨论】:

  • 试试,alert('你点击了' +myItem);
  • 为什么我在 html 中看不到任何ids?
  • 请编辑您的问题以显示外部 html - 您当前的代码在任何地方都没有显示任何 id 属性或字符串 science。我猜这包含在一个 parenet 元素中,但要回答我需要查看该元素
  • @Rayon Dabre : 为什么你删除了添加的标记 OP??
  • @MilindAnantwar,正在批准 Rajesh 的编辑。道歉..

标签: javascript jquery html html-table


【解决方案1】:

您的markup 中没有id 属性。你正在处理的只是innerText

$('td').click(function() {

  var myItem = $(this).text();
  alert('u clicked ' + myItem);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
  <tr>
    <td>Computer</td>
  </tr>
  <tr>
    <td>maths</td>
  </tr>
  <tr>
    <td>physics</td>
  </tr>
</table>

【讨论】:

  • "u clicked science" 强烈建议问题中未显示父元素。 science 没有出现在任何文本节点中,加上 computer, maths and physics 都可以被松散地认为是科学领域,但最终它是任何人的猜测,除非 OP 响应
【解决方案2】:

您的标记无效。在最后一个 tr 关闭标记之后添加额外的关闭 div。你需要删除它。

您需要注意的是元素的文本,而不是父 ID。使用 .text() 以及单击的 td 元素 jquery 上下文:

$('td').click(function(){
 myItem=$(this).text();
 alert('u clicked ' +myItem);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table>


<tr><td>Computer</td></tr>


<tr><td>maths</td></tr>

<tr><td>physics</td></tr>

</table>

【讨论】:

    【解决方案3】:

    试试这个:

        $('td').click(function () {
            alert('u clicked ' + $(this).text());
        });
    

    【讨论】:

      【解决方案4】:

      正如我已经评论过的,您在tr 中缺少ID。我已经添加了几个tds 用于演示。

      $('td').click(function() {
        var myId = $(this).parent().attr("id");
        var myItem = $(this).text();
        alert('u clicked ' + myId);
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
      <table>
        <tr id="IT">
          <td>Computer</td>
        </tr>
        <tr id="General">
          <td>maths</td>
          <td>History</td>
        </tr>
        <tr id="Science">
          <td>physics</td>
          <td>Chemistry</td>
          <td>Biology</td>
        </tr>
      </table>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-19
        • 2020-08-11
        • 2015-08-12
        • 2013-03-22
        • 1970-01-01
        • 2020-10-20
        • 1970-01-01
        • 2020-01-27
        相关资源
        最近更新 更多