【问题标题】:JQuery get classes values inside of classesJQuery获取类内的类值
【发布时间】:2016-02-27 18:05:25
【问题描述】:

我有以下html:

<tr class="row">
    <td>row 1</td>
    <td><input type="text" class="user-input"></td>
    <td><input type="text" class="user-input"></td>
</tr>

<tr class="row">
    <td>row 2</td>
    <td><input type="text" class="user-input"></td>
    <td><input type="text" class="user-input"></td>
</tr>

假设表单有以下输入

第 1 行 |一个 | b

第 2 行 | c | d

我想从表中获取以下对象:

[{a,b}, {c,d}]

我尝试使用 .each 来获取值

$(".row .user-input").each( function() {
    ...
});

但是我只能通过使用上面的行来获得 [a,b,c,d] 。我想知道是否有办法为此目的使用类似嵌套的 each。

感谢您的帮助!

【问题讨论】:

    标签: jquery class each


    【解决方案1】:

    我认为您需要的是一个数组数组,然后您可以迭代每一行,然后迭代该行中的每个输入,例如

    var values = $('.row').map(function() {
      return [$(this).find('.user-input').map(function() {
        return $(this).val();
      }).get()];
    }).get();
    
    $('pre').html(JSON.stringify(values));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
      <tr class="row">
        <td>row 1</td>
        <td>
          <input type="text" class="user-input" value="a">
        </td>
        <td>
          <input type="text" class="user-input" value="b">
        </td>
      </tr>
    
      <tr class="row">
        <td>row 2</td>
        <td>
          <input type="text" class="user-input" value="c">
        </td>
        <td>
          <input type="text" class="user-input" value="d">
        </td>
      </tr>
    </table>
    
    <pre></pre>

    【讨论】:

      【解决方案2】:
        arr = [];
        $('.row').each(function(o) {
          var inner = [];
          $('.user-input', this).each(function(e) {
            inner.push($(this).val());
          });
          arr.push(inner);
        });
      

      -

      <table>
        <tr class="row">
         <td>row 1</td>
         <td>
           <input type="text" class="user-input" value="a">
         </td>
         <td>
           <input type="text" class="user-input" value="b">
         </td>
       </tr>
      
       <tr class="row">
         <td>row 2</td>
         <td>
           <input type="text" class="user-input" value="c">
         </td>
         <td>
          <input type="text" class="user-input" value="d">
         </td>
       </tr>
      
      </table>
      

      笔在这里:http://codepen.io/anon/pen/OyYdpq

      【讨论】:

        猜你喜欢
        • 2011-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多