zoukankan      html  css  js  c++  java
  • 使用Jquery1.9 版本 来实现全选

      

      在使用Jquery实现全选以及反选的时候, 使用attr()实现的时候,在浏览器第一次运行可以全选,但是第二次再全选,不管用。

     通过查找资料,用 prop()方法代替attr()方法就行了。

     注意:  

           Jquery 1.6之后,可以通过attr方法去获得属性,通过prop方法去获得特性.

          在遇到要获取或设置checked,selected,readonly和disabled等属性时,用prop方法.

    jquery1.6中新加了一个方法prop(),官方解释只有一句话:获取在匹配的元素集中的第一个元素的属性值。

    大家都知道有的浏览器只要写disabled,checked就可以了,而有的要写成disabled = "disabled",checked="checked",比如用attr("checked")获取checkbox的checked属性时选中的时候可以取到值,值为"checked"但没选中获取值就是undefined。

    jq提供新的方法“prop”来获取这些属性,就是来解决这个问题的,以前我们使用attr获取checked属性时返回"checked"和"",现在使用prop方法获取属性则统一返回true和false。

    那么,什么时候使用attr(),什么时候使用prop()?
    1.添加属性名称该属性就会生效应该使用prop();
    2.是有true,false两个属性使用prop();
    3.其他则使用attr();

    以下是官方建议attr(),prop()的使用:

    Attribute/Property.attr().prop()
    accesskey  
    align  
    async
    autofocus
    checked
    class  
    contenteditable  
    draggable  
    href  
    id  
    label  
    location ( i.e. window.location )
    multiple
    readOnly
    rel  
    selected
    src  
    tabindex  
    title  
    type  
    width ( if needed over .width() )  

    以下是实现全选以及反选的Html代码,要引用Jquery脚本。Jquery1.6以上都行

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src="jquery-1.9.1.js"></script>
    </head>
    <body>
    <input type="checkbox" value="全选" id="cbAll" name="cbArea">全选<br/>
    <input type="checkbox" value="洛龙区" name="a">洛龙区
    <input type="checkbox" value="涧西区" name="a">涧西区
    <input type="checkbox" value="吉利区" name="a">吉利区
    <input type="checkbox" value="西工区" name="a">西工区
    <input type="checkbox" value="宜阳县" name="a">宜阳县
    <input type="checkbox" value="老城区" name="a">老城区
    <input type="checkbox" value="回族区" name="a">回族区
    <input type="checkbox" value="偃师" name="a">偃师
    <input type="checkbox" value="哈哈区" name="a">哈哈区
    <input type="checkbox" value="洛宁区" name="a">洛宁区
    
    </body>
    </html>
    
    
    <script type="text/javascript">
        $(function () {
            $("#cbAll").click(function () {
                if($("#cbAll").is(":checked")) {
                    $(":checkbox").prop("checked",true);
                }
                else {
                    $(":checkbox").prop("checked", false);
                }
    
            });
    
            $(":checkbox").click(function () {
                if (!$(this).is(":checked")) {
                    $("#cbAll").prop("checked", false);
                }
    
            });
        })
    </script>
  • 相关阅读:
    背水一战 Windows 10 (26)
    背水一战 Windows 10 (25)
    背水一战 Windows 10 (24)
    背水一战 Windows 10 (23)
    背水一战 Windows 10 (22)
    背水一战 Windows 10 (21)
    背水一战 Windows 10 (20)
    背水一战 Windows 10 (19)
    背水一战 Windows 10 (18)
    背水一战 Windows 10 (17)
  • 原文地址:https://www.cnblogs.com/luoyangcn/p/3871519.html
Copyright © 2011-2022 走看看