【问题标题】:how to get parent div from element inside? [duplicate]如何从元素内部获取父div? [复制]
【发布时间】:2021-11-01 07:08:52
【问题描述】:

我正在获取动态输入 id custom_field_42,我需要获取表单组 div 以将显示从无更改为阻止,我该怎么做?

<div class="form-group row g-mb-5" style="display:none;">
  <label for="custom_field_42" class="col-sm-2 col-form-label g-mb-10 text-right">insteructyor</label>
  
  <div class="col-sm-10">
    <input type="text" class="form-control u-form-control rounded-0 custom_field_input" id="custom_field_42" name="insteructyor" placeholder="insteructyor">
  </div>
</div>

我试过了,还是不行。

$('#custom_field_42').closest('.form-group').show()

社区编辑...

实际上,这是可行的:

$('#custom_field_42').closest('.form-group').show();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="form-group row g-mb-5" style="display:none;">
  <label for="custom_field_42" class="col-sm-2 col-form-label g-mb-10 text-right">insteructyor</label>

  <div class="col-sm-10">
    <input type="text" class="form-control u-form-control rounded-0 custom_field_input" id="custom_field_42" name="insteructyor" placeholder="insteructyor">
  </div>
</div>

【问题讨论】:

  • 您的代码运行良好。见上面的 sn-p。
  • @isherwood 是的,我又试了一次,它在我的原始代码中运行良好。谢谢

标签: javascript jquery


【解决方案1】:

您可以使用Element.closest 找到第一个匹配选择器的父元素,在我们的例子中是.row

const input = custom_field_42;
input.closest('.row').style.display="block";
<div class="form-group row g-mb-5" style="display:none;">

  <label for="custom_field_42" class="col-sm-2 col-form-label g-mb-10 text-right">insteructyor</label>

  <div class="col-sm-10">

    <input type="text" class="form-control u-form-control rounded-0 custom_field_input" id="custom_field_42" name="insteructyor" placeholder="insteructyor">

  </div>
</div>

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 1970-01-01
    • 2021-10-30
    • 2016-09-02
    • 2019-02-19
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 2019-08-06
    相关资源
    最近更新 更多