zoukankan      html  css  js  c++  java
  • input checkbox问题和li里面包含checkbox

    <input type="checkbox" id="checkbox1"/>

    $("input#checkbox1").click(function() {
    console.log($(this).attr('checked'));
    console.log($(this).prop("checked"));
    });

    点击checkbox输出:

    undefined  
    true  
    再次点击。
    undefined  
    false
    说明如果没有设置checked,我们就不要用attr("checked")这个属性。
    注意:input和#checkbox1中间不要有空格,有空格的话就表示后代了。
     
    我们经常需要li或span包含一个checkbox,不管点击checkbox或li都会触发相应的事件,如背景色变色。
    <ul>
        <li><input type="checkbox" name="" id=""/>li1</li>
        <li><input type="checkbox" name="" id=""/>li2</li>
        <li><input type="checkbox" name="" id=""/>li3</li>
        <li><input type="checkbox" name="" id=""/>li4</li>
    </ul>

    js如下:

    $("ul li").click(function(){
            var $input=$(this).find("input");
            if($input.prop("checked"))
            {
                $input.prop("checked",false);
                $(this).css("background-color","");
            }
            else
            {
                $input.prop("checked",true);
                $(this).css("background","red");
            }
        });

    点击li可以,为什么点击checkbox不行。原因在于你勾选后,input.prop("checked")就为真了,这时就又取消掉了。导致你勾选不上。

    这么做也不行:

      $("ul li").click(function(){
            var $input=$(this).find("input");
            var count=1;
         
            if(count%2==0)
            {
                $input.prop("checked",false);
                $(this).css("background-color","");
    
            }
            else
            {
                $input.prop("checked",true);
                $(this).css("background","red");
    
            }
            count++;
        });

    因为每次点击count都重新赋值。

    这里可以用each来在每个li函数定义之前加count:

     $("ul li").each(function(){
            var count=1;
            $(this).click(function(){
                var $input=$(this).find("input");
                if(count%2==0)
                {
                    $input.prop("checked",false);
                    $(this).css("background-color","");
    
                }
                else
                {
                    $input.prop("checked",true);
                    $(this).css("background","red");
    
                }
                count++;
            });
        });
     
  • 相关阅读:
    清除陷入CLOSE_WAIT的进程
    Eclipse
    远程连接elasticsearch遇到的问题
    Linux环境Nginx安装
    CentOS安装mysql
    py2exe使用方法
    Python3.4如何读写Excel
    getPhysicalNumberOfCells 与 getLastCellNum的区别
    浅析MySQL中exists与in的使用
    【MongoDB for Java】Java操作MongoDB
  • 原文地址:https://www.cnblogs.com/youxin/p/3885496.html
Copyright © 2011-2022 走看看