javascript - 通过 jQuery 获取最接近的内容

标签 javascript jquery closest

我在使用 jQuery 的 closest() 时遇到问题。当我想打印一个示例时,例如 d 变量,我收到未定义的错误。

$(".eb").click(function() {
  var d = $(this).closest(".contact-info");
  var t = $(this).closest(".contact-tell");
  var n = $(this).closest(".contact-name");
  var i = $(this).closest(".contact-id");
  console.log(d.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr>
    <td class="contact-id">
      <?php echo $value[0]; ?>
    </td>
    <td class="contact-name">
      <?php echo $value[1]; ?>
    </td>
    <td class="contact-tell">
      <?php echo $value[2]; ?>
    </td>
    <td class="contact-info">
      <?php echo $value[3]; ?>
    </td>
    <td class="td-actions">
      <a href="?IDD=<?php echo $value[0]." &owner=".$_SESSION['username'];?>">
        <i class="glyphicon glyphicon-trash"></i>
      </a>

      <a href="#" class="eb" data-uid="<?php echo $value[0]; ?>" data-toggle="modal" data-target=".bs-example-modal-lg">
        <i class="glyphicon glyphicon-edit"></i>
      </a>
    </td>
  </tr>
</table>

最佳答案

closest()只看祖宗。 .contact-info 不是 .eb 的祖先。

查找最近的tr(最近的共同祖先),然后在以下范围内搜索:

var d=$(this).closest("tr").find(".contact-info")

稍微更有效的方法...

$(".eb").click(function() {
  var $ancestor = $(this).closest("tr"); // Cache 'tr' so we don't have to look it up every time
  var d = $ancestor.find(".contact-info");
  var t = $ancestor.find(".contact-tell");
  var n = $ancestor.find(".contact-name");
  var i = $ancestor.find(".contact-id");
  console.log(d.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr>
    <td class="contact-id">
      echo $value[0];
    </td>
    <td class="contact-name">
     echo $value[1];
    </td>
    <td class="contact-tell">
      echo $value[2];
    </td>
    <td class="contact-info">
      echo $value[3];
    </td>
    <td class="td-actions">
      <a href="#">
        <i class="glyphicon glyphicon-trash"></i>
      </a>

      <a href="#" class="eb" data-uid="#" data-toggle="modal" data-target=".bs-example-modal-lg">
        BUTTON
        <i class="glyphicon glyphicon-edit"></i>
      </a>
    </td>
  </tr>
</table>

关于javascript - 通过 jQuery 获取最接近的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42280743/

相关文章:

javascript - 在运行 javascript 时防止 Windows 提示打开

jquery - Safari - 错误 : Syntax error, 无法识别的表达式:输入[data-card-type =“payment-one”

javascript - 表单在 onsubmit 函数完成之前提交

jQuery : Get the index of non-siblings elements of the closest class

jquery - 为什么我无法触发提交按钮最接近的表单?

java - 安卓 : SQLite : Find closest value from a table

javascript - Angular ng-repeat $index

javascript - jQuery 超大 AfterAnimation

javascript - 如何正确地将用户名和密码从reactjs传递到后端进行身份验证?

jquery - 使用 JSZip 下载图像会导致浏览器崩溃