簡體   English   中英

使用jQuery遍歷:遍歷子級

[英]Traversing with jQuery: cycle over children

大家好,我有一個類似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”(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.

       }
    });

我們都可以討論這有多“有效”,但是考慮到您的頁面可能有多小,我認為使它變得如此簡單是合理的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM