javascript - 父级的 JQuery 比较 ('tr) and find(' tr :first') not working

标签 javascript jquery html

当单击表格的某个单元格时,我想设置该单元格的内容,但前提是该单元格既不在第一行也不在第一列。

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

  console.log($(this).parents('tr'));
  console.log($('#matrix').find('tr:first'));
  console.log($('#matrix').find('tr:first') == $(this).parents('tr'));

  if ($(this).parents('tr') != $('#matrix').find('tr:first')) {

    console.log("is ok");
    if ($(this).text() != "x") { // Connect
      $(this).text("x");
      alert("Connecting " +
        $('td:first', $(this).parents('tr')).text() +
        " with " +
        $('tr:first', $(this).parents('td')).text());
    } else { //Disconnect
      $(this).text("");
      alert("Disconnecting Endpoint " +
        $('td:first', $(this).parents('tr')).text() +
        " with Endpoint " +
        $('tr:first', $(this).parents('td')).text());
    };

  }; // row/columns > 0 only
}); // click()
td {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="matrix" border="0">
  <tr>
    <td>Matrix</td>
    <td>_name_</td>
    <td>_name_</td>
  </tr>
  <tr>
    <td>_name_</td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>_name_</td>
    <td></td>
    <td></td>
  </tr>

</table>

Firefox 调试控制台突出显示完全相同的元素,但是

console.log( $(this).parents('tr') == $('#matrix').find('tr:first') );

无论我点击哪个单元格,始终显示 false。

我做错了什么?

最佳答案

也许两个指向同一个 dom 元素,但对象引用会不同。要检查相等性,请使用 is() jQuery 中的方法。

console.log( $(this).parents('tr').is($('#matrix').find('tr:first')));

<小时/> 或者通过使用索引或 get() 来比较 DOM 对象方法。

console.log( $(this).parents('tr')[0] == $('#matrix').find('tr:first')[0]);
// or
console.log( $(this).parents('tr').get(0) == $('#matrix').find('tr:first').get(0));
<小时/>

更新:此外,您可以通过仅为需要更新内容的td元素绑定(bind)点击事件来减少代码。在哪里使用 :nth-child伪类选择器(纯CSS选择器)来过滤td。

$('#matrix tr:nth-child(n + 2) td:nth-child(n + 2)').click(function() {
  //  use text method with callback to update text based on the existing content
  $(this).text(function(i, txt) {
    return txt === 'x' ? '' : 'x';
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="matrix" border="0">
  <tr>
    <td>Matrix</td>
    <td>_name_</td>
    <td>_name_</td>
  </tr>
  <tr>
    <td>_name_</td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>_name_</td>
    <td></td>
    <td></td>
  </tr>
</table>

关于javascript - 父级的 JQuery 比较 ('tr) and find(' tr :first') not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47593455/

相关文章:

html - 从 DIV 隐藏滚动条

javascript - 根据javascript中的给定索引对数组重新排序

javascript - 使用 jQuery 在 keyUp 上包装 <span> 中的单个字符

javascript - 如何在从 localStorage 中的变量加载页面时设置基于 UL 的下拉列表的值?

c# - 使用jquery ajax上传文件

html - 将 DIV 调整为表格中的最大高度

javascript - 检查innerHTML是否为空

javascript - 无法解析 strip Angular 依赖注入(inject)

javascript - getFullYear 返回前一年的第一天

javascript - 从元素复制 HTML,用 jQuery 替换文本,然后附加到元素