【问题标题】:How can I get the child element value using jquery looping?如何使用 jquery 循环获取子元素值?
【发布时间】:2021-05-07 23:16:23
【问题描述】:

我想动态获取子元素。我正在循环通过 div 标签来获取值。但它不起作用。

<div class="pg">
  <div class="row">
    <div class="col-3">
      <div class="fg">
        <input type="text" xl="12" value="a">
      </div>
      <div class="fg">
        <input type="text" xl="34" value="b">
      </div>
    </div>
  </div>
</div>

动态获取值的javascript函数

如果 row 和 col div 不存在,则此代码有效。但是当它们被包括在内时,它根本不起作用。任何人都可以帮我解决这个问题!

$(".pg").each(function(){
   $(this).children(".fg").each(function() {
       console.log($(this).attr('xl'));
   });  
});

【问题讨论】:

  • xl 不是有效属性。这应该是 data-* 属性 -> data-xl="..."
  • 按照@Andreas 所说的操作后,您可以使用$('input[data-xl]') 选择输入
  • 但是在实现网格后循环时。我无法获取值。
  • @lnx 考虑更新问题中的代码?

标签: javascript html jquery jquery-ui jquery-plugins


【解决方案1】:

首先使用children(),将只返回直接子级,而不是深度搜索,

其次,使用data-xl而不是xl,更多关于数据属性的信息here

另外,循环正在访问 input 的父 div,所以请改用".fg input"

搜索使用find(),然后更改选择器以直接访问您的输入,.find(".fg input")

请参阅下面的工作 sn-p :

$(".pg").each(function() {
  $(this).find(".fg input").each(function() {
    console.log($(this).val() ,"=", $(this).data('xl'));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pg">
  <div class="row">
    <div class="col-3">
      <div class="fg">
        <input type="text" data-xl="12" value="a">
      </div>
      <div class="fg">
        <input type="text" data-xl="34" value="b">
      </div>
    </div>
  </div>
</div>

<div class="pg">
  <div class="row">
    <div class="col-3">
      <div class="fg">
        <input type="text" data-xl="15" value="c">
      </div>
      <div class="fg">
        <input type="text" data-xl="84" value="d">
      </div>
    </div>
  </div>
</div>

【讨论】:

  • 求帮助。我所有的疑问和解释都帮助我解决了这个问题。还有@Andreas 和 Evolutionxbox 帮助我。
猜你喜欢
  • 1970-01-01
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
  • 2013-09-22
  • 2021-05-05
  • 2013-12-21
  • 2019-12-28
  • 2021-12-05
相关资源
最近更新 更多