day17--多选、反选、全选使用jquery

1、使用prop方法

(1)$('#tb :checkbox').prop('checked');    获取值

  $('#tb :checkbox').prop('checked',true);    设置值

(2)jquery方法内置循环:$('#tb :checkbox').xxxx    例如 $('#tb :checkbox').prop('checked',false);

(3)$('#tb :checkbox').each(function(k)){   //k是当前索引;this,Dom中当前元素;$(this),jquery中当前元素}

(4)var v=条件?真值:假值

2、多选,全选,反选实例

(1)页面布局及信息如下:

     <input type="button" value="全选" onclick="CheckAll();"/>
        <input type="button" value="取消" onclick="CancleAll();"/>
        <input type="button" value="反选" onclick="ReverseAll();"/>
        <table border="1">
            <thead>
                <tr>
                    <th>选项</th>
                    <th>ip</th>
                    <th>port</th>
                </tr>
            </thead>
            <tbody id="tb">
                <tr>
                    <td><input type="checkbox"/></td>
                    <td>1.1.1.1</td>
                    <td>80</td>
                </tr>
                <tr>
                    <td><input type="checkbox"/></td>
                    <td>1.1.1.1</td>
                    <td>80</td>
                </tr>
                <tr>
                    <td><input type="checkbox"/></td>
                    <td>1.1.1.1</td>
                    <td>80</td>
                </tr>
            </tbody>
        </table>

现在我们需要实现的功能是,点击全选时,按钮全部选中;点击取消时,取消当前选中;

(2)全选与取消的功能相反,代码相似,使用jquery实现如下:

     <script src="jquery-1.12.4.js"></script>
        <script>
            function CheckAll(){
                $('#tb :checkbox').prop('checked',true);
            }
            function CancleAll(){
                $('#tb :checkbox').prop('checked',false);
            }

(3)反选实现方法有三种:

  (a)使用Dom方法:

function ReverseAll(){
                $('#tb :checkbox').each(function(k){
                    // this,代指当前循环的每一个元素;k是索引的下标
                    // Dom
                    // console.log(this);     //this是Dom对象,可以通过控制台输出来区分
                    // console.log($(this));   //$(this)是Dom对象
                    if(this.checked){
                        this.checked=false;
                    }else{
                        this.checked=true;
                    } 
                })
            }

  (b)使用jquery方法:

function ReverseAll(){
                $('#tb :checkbox').each(function(k){
                    //jquery
                    if($(this).prop('checked')){
                        $(this).prop('checked',false);
                    }else{
                        $(this).prop('checked',true);
                    }  
                })
            }

  (c)使用三元运算:

function ReverseAll(){
                $('#tb :checkbox').each(function(k){
                    //三元运算var v=条件?真值:假值    如果条件是真的,将第一个值赋值给v;如果条件是假的,将第二个值赋值给v
                    var v=$(this).prop('checked')?false:true;
                    $(this).prop('checked',v);
                })
            }

以上三种实现反选的代码不同,但结果相同。

猜你喜欢

转载自www.cnblogs.com/wuxiaoru/p/12641434.html
今日推荐