遍历jQuery:循环遍历孩子

时间:2015-03-17 10:49:07

标签: javascript jquery html

大家好我有这样的html结构:

<tr>
    <td>
        <div class="sigle-sz">
            <span class="label-sz">36</span> <input class="" type="tel" value="" name="">
            <div class="available yes">
                <i aria-hidden="true" class="availablespot"></i>
            </div>
        </div> <!-- /sigle-sz -->
    </td>
    <td>
        <div class="sigle-sz">
            <span class="label-sz">38</span> <input class="" type="tel" value="" name="">
            <div class="available yes">
                <i aria-hidden="true" class="availablespot"></i>
            </div>
        </div> <!-- /sigle-sz -->
    </td>
    <td>
        <div class="sigle-sz">
            <span class="label-sz">40</span> <input class="" type="tel" value="" name="">
            <div class="available yes">
                <i aria-hidden="true" class="availablespot"></i>
            </div>
        </div> <!-- /sigle-sz -->
    </td>
</tr>

我创建了一个像这样的jQuery函数:

<script>
    function pippo() {

        //code here

    }

    $( document ).ready(function() {

        $( ".sigle-sz" ).on('change', function() {
            pippo();
        });
    });
</script>

我会在函数“pippo()”中循环<td>标记中的<tr>元素,并将输入值保存在变量中。

如果this$( ".sigle-sz" )元素,我该如何进行此循环?

我在这里放了我当前的代码:https://jsfiddle.net/ydrunbzz/

2 个答案:

答案 0 :(得分:0)

您可以使用$.each() jQuery function

var values;  // define global var to use everywhere

function pippo(myClass) {
    $.each(("." + myClass), function (index, value) {
        values += value;
    });
}

答案 1 :(得分:0)

使用.each()循环解决此问题的方法。如果你是新手,我认为拥有一个非常易读的循环非常重要,否则你会很快失去轨道。

1)全局变量

2)首先确保当有人在输入中写入内容时收集数据!

3)pippo函数将清除全局变量“arrSigle”(Array Sigle的缩写),并确保它只填充当前写下的数字

    $(document).ready(function () {

       //1
       var arrSigle= [];

       //2
       $( ".sigle-sz" ).find("input").on("change", function(){
            pippo();
//just FYI, the "change" only fires when an input has a new value, and lose focus
// by any means. If it annoys you to have to click out of the box for pippo()
//to run, you might want to use "onkeyup" instead of "change".
//it will fire every time someone lets go of a key while inside the input

       })

       //3
       function pippo(){
           arrSigle.length = 0; //this clears the variable
           $( ".sigle-sz" ).find("input").each(function(){
                arrSigle.push($(this).val()); 
                //this itterates over all the inputs and pushes them into the
                //global variable.
           })
           //If you want some function to run right after all the
           //numbers has been gathered, put it right under this comment.

       }
    });

我们都可以讨论这是多么“有效”,但考虑到你的网页可能有多小,我认为让它变得如此简单是合理的