遍历 jQuery:循环遍历子项

Traversing with jQuery: cycle over children

本文关键字:遍历 jQuery 循环      更新时间:2023-09-26

嗨,我有一个这样的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() "中循环<tr>标签中的<td>元素并将输入值保存在变量中。

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

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

您可以使用$.each() jQuery 函数:

var values;  // define global var to use everywhere
function pippo(myClass) {
    $.each(("." + myClass), function (index, value) {
        values += value;
    });
}

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

1) 全局变量

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

3)pippo函数将清除全局变量"arrSigle"(数组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.
       }
    });

我们都可以讨论这有多"有效",但考虑到你的页面可能有多小,我认为让它变得如此简单是完全合理的。