jquery 每个表单元素 - 如何获取表单中的下一个、上一个元素?

jquery each for form elements - how to get next, prev element in form?

我有一个表单,其中每个输入元素都有一个带有文本的标签,一些标签有一个带有 class 'required' 的跨度项,标签和文本之间可能还有一些 div输入,例如

<label for="diameter">D<span class="required">Required</span></label>
<div ...
    <input type="text" id="diameter" name="diameter" value="20" />

我需要检查所有带有所需跨度标签的输入。我可以像

一样旋转所有跨度
$('form .required').each(function(index, element) {
});

其中 'element' 是跨度。但是我如何获得关联的输入呢? None 以下作品:

element.next('input[type="text"]')
$(element).next('input[type="text"]')

从其 for 属性(可通过 jQuery 上的 .attr 或元素上的 .htmlFor 访问),您可以获得它指向的 ID,并使用ID,你可以select你想要的元素:

$('.required').each((_, span) => {
  const $input = $('#' + $(span).parent()[0].htmlFor);
  console.log($input.val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="diameter">D<span class="required">Required</span></label>
<div>
  <input type="text" id="diameter" name="diameter" value="20">
</div>

如果您需要使用.next,您可以使用:

$('.required').each((_, span) => {
  const $span = $(span);
  const $parentLabel = $span.parent();
  const forVal = $parentLabel[0].htmlFor;
  const $input = $parentLabel.next('div').find('#' + forVal);
  console.log($input.val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="diameter">D<span class="required">Required</span></label>
<div>
  <input type="text" id="diameter" name="diameter" value="20">
</div>

因为spanlabel元素里面,你不能直接使用next方法。

首先需要使用parent方法遍历到父元素

 $('form .required').each(function (index, element) {
     var inputElement = $(element).parent().next('div').find('input[type="text"]');
 });