zoukankan      html  css  js  c++  java
  • 问题:循环元素,被选中元素个数,全选

    一段时间不写js都有点忘记了,这里看几个常见的js,涉及到循环,计算元素个数,checkbox选中等问题,首先是html元素

    <div class="content border p05">
                <div><input type="checkbox" id="selectAll" name="selectAll">Select All</div>
                <table>
                    <tbody>
                        <tr style="text-align: left;">
                            <th>&nbsp;</th>
                            <th style="10%;">Qty</th>
                            <th>Descritpion</th>
                            <th>Item ID</th>
                        </tr>
                                            <tr>
                            <td><input type="checkbox" class="item_id" value="29714200" name="item_id[]" style=" 12px;"></td>
                            <td>25</td>
                            <td>Personalized Holiday CardsPersonalized Holiday Cards - 5" x 7" Cardstock - Standard Cardstock - White Envelopes</td>
                            <td>29714200</td>
                        </tr>
                                            <tr>
                            <td style="text-align: center;padding-top:30px;" colspan="4"><div class="btn large step1">Submit</div></td><td>
                        </td></tr>
                    </tbody>
                </table>
            </div>

    1.全选问题

            $('#selectAll').click(function() {
                if($(this).attr('checked') == 'checked') {
                    $("input[name='item_id[]']").attr("checked", true);
                    //$('.item_id').attr('checked', true);
                    var length = $('.item_id').length;
                    $('#number').html(length);                
                } else {
                    $('.item_id').removeAttr('checked');
                    $('#number').html(0);
                }
            });

    注意判断checkbox是否选中是"if($(this).attr('checked') == 'checked')",不是if($(this).attr('checked') == ture),但是很奇怪的是可以用true赋值$("input[name='item_id[]']").attr("checked", true);

    2.判断checkbox选中个数

    $('.item_id:checked').length,这个写法很简洁的

    3.循环元素,绑定函数

                var num = 0;
                $.each($('.item_id'),function(i,v){
                    if($(this).attr('checked') == 'checked'){
                        num++;
                    }
                });
                if(0 == num){
                    alert('please select item(s)');
                    return false;
                }

    其实这写法有点啰嗦,可以直接if(0==$('.item_id:checked').length){ alert('please select item(s)'); }

  • 相关阅读:
    报表
    重构改善既有代码设计--重构手法02:Inline Method (内联函数)& 03: Inline Temp(内联临时变量)
    重构改善既有代码设计--重构手法01:Extract Method (提炼函数)
    httpclient 学习
    JAVA中反射机制六(java.lang.reflect包)
    JAVA中反射机制五(JavaBean的内省与BeanUtils库)
    JAVA中反射机制四
    JAVA中反射机制三
    JAVA中反射机制二
    JAVA中反射机制一
  • 原文地址:https://www.cnblogs.com/tylerdonet/p/4179795.html
Copyright © 2011-2022 走看看