我在使用 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/