• 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++;
            });
        });
     
  • 相关阅读:
    如何用Python实现网络请求库中的UR解析器,面试必学
    为什么有人说 Python 多线程是鸡肋?
    router-view 与 动态组件 区别
    keep-alive
    vue 客户端渲染和服务端渲染
    js 数组对象深拷贝
    vue template标签
    Jquery中的日历插件
    HTML5中的canvas基本概念及绘图
    HTML5中的音视频处理
  • 原文地址:https://www.cnblogs.com/youxin/p/3885496.html
Copyright © 2020-2023  润新知