如何选择 $(this) 之后的下一个元素

How can I select next element after $(this)?

本文关键字:之后 下一个 元素 this 选择 何选择      更新时间:2023-09-26

我有这个代码:

$("td").on("click", function(){
  var result = $(this).closest('table').siblings('form').find('input[name="inputname"]').attr('value');
  alert(result);
});
td {
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
    <tr>
        <td>click</td>
    <tr>
</tbody>
</table>
<form>
<input name = 'inputname' value = "10">
</form>
<form>
<input name = 'inputname' value = "12">
</form>

当您单击click 时,它会提醒10。一切都很好,10正是我需要得到的。但不知道自己为什么对.siblings('form')有不好的预感,因为二form也在那个table的兄弟姐妹范围内。虽然我只需要选择table下的那个form,但只有一个(不是第二个form)。

同样,输出是正确的,在这种情况下,我想要的只是.siblings(form)的替代方案,有吗?

换句话说,我如何在jQuery中定义它?

$(this).closest('table')./* next form */.find('input[name="inputname"]').attr('value');

siblings('form')返回 HTML 示例的两个匹配项。只是因为你用一个调用来结束链attr,你只能得到一个结果。如文档中所述:

.attr() 方法仅获取匹配集中第一个元素的属性值。

请注意,siblings还会向后查找匹配项,因此,如果您的表格前面有一个表单,它将在那里查找输入框。

您可以使用next('form').first()而不是siblings('form')来确保只向前看,并且只参加第一场比赛。

你的坏感觉是对的。有一天,你的设计师想把一些元素包装成其他一些元素,突然程序将停止工作
。主要是因为.siblings("form")很可能不再是form的布斯,而是<div>(持有form)。

我会选择自定义data-*属性:

$("[data-click]").on("click", function() {
  var target = $(this).data("click");
  var result = $("[data-target='"+target+"']").find("[name=inputname]").val();
  alert(result);
});
[data-click] { /* how cool is that ;) */
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td data-click="form_1">click</td>
    <tr>
  </tbody>
</table>
<form data-target="form_1">
  <input name = 'inputname' value = "10">
</form>
<form data-target="form_2">
  <input name = 'inputname' value = "12">
</form>

也许将data-target固定在input元素上会是一个更好的主意!

这个呢?

$("td").on("click", function(){
  var result = $(this).closest('table').next('form').siblings('form').find('input[name="inputname"]').attr('value');
  alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
    <tr>
        <td>click</td>
    <tr>
</tbody>
</table>
<form>
<input name = 'inputname' value = "10">
</form>
<form>
<input name = 'inputname' value = "12">
</form>