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++;
            });
        });
     
  • 相关阅读:
     一、cocos2dx之如何优化内存使用(高级篇)
    latex模版&&c++ STL用法&&画图网站
    HDU 3480 Division
    HDU 3045 Picnic Cows
    HDU 2993 MAX Average Problem
    HDU 3507 Print Article
    Luogu P2900 [USACO08MAR]土地征用Land Acquisition
    浅谈斜率优化
    POJ 2559 Largest Rectangle in a Histogram
    【计算几何】求半平面交的面积
  • 原文地址:https://www.cnblogs.com/youxin/p/3885496.html
Copyright © 2011-2022 走看看