• 日常问题记录--jquery中HTML元素本身固有属性用prop,自定义的DOM属性,在处理时,使用attr方法


    jquery中,在设置多个radio的唯一选中时,prop与attr表现不同。次啊面代码中如果将prop换为attr,则页面所有checkbox在取消选中后,都不能再次选中;

    原因:

    • 对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
    • 对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
    <script language="javascript">
    <!-- 
    function checkBox(obj) {
    // 只有当选中的时候才会去掉其他已经勾选的checkbox,所以这里只判断选中的情况
        if (obj.is(":checked")) {
             // 先把所有的checkbox 都设置为不选种
            $('input.mybox').prop('checked', false);
            // 把自己设置为选中
            obj.prop('checked',true);
        }
    }
    //-->
    </script>
    

      

    <input type="checkbox" class="mybox" onclick="checkBox($(this));"/>
    <input type="checkbox" class="mybox" onclick="checkBox($(this));"/>
    <input type="checkbox" class="mybox" onclick="checkBox($(this));"/>
    <input type="checkbox" class="mybox" onclick="checkBox($(this));"/>
    <input type="checkbox" class="mybox" onclick="checkBox($(this));"/>
    <input type="checkbox" class="mybox" onclick="checkBox($(this));"/>
    <input type="checkbox" class="mybox" onclick="checkBox($(this));"/>
    <input type="checkbox" class="mybox" onclick="checkBox($(this));"/>
    <input type="checkbox" class="mybox" onclick="checkBox($(this));"/>
    <input type="checkbox" class="mybox" onclick="checkBox($(this));"/>
    <input type="checkbox" class="mybox" onclick="checkBox($(this));"/>
    <input type="checkbox" class="mybox" onclick="checkBox($(this));"/>
    <input type="checkbox" class="mybox" onclick="checkBox($(this));"/>
    

      

    再举一个例子:

    <input id="chk1" type="checkbox" />是否可见
    <input id="chk2" type="checkbox" checked="checked" />是否可见

    像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此需要使用prop方法去操作才能获得正确的结果。

    $("#chk1").prop("checked") == false
    $("#chk2").prop("checked") == true

    如果上面使用attr方法,则会出现:

    $("#chk1").attr("checked") == undefined
    $("#chk2").attr("checked") == "checked
    不会炒菜的非专业测试人员
  • 相关阅读:
    SQL Server 2005 Integration Services (SSIS)数据源之MySQL
    SQL Server 2005 Integration Services (SSIS)数据源之Sybase
    oracle10g 监听服务无法启动
    创建一个People类型,有年龄、工资、性别三个属性。 定义一个方法叫做找对象,找对象方法传过来一个人;
    基于组件的C#农历算法
    ASP.NET中实现中文简/繁体自动转换的类
    最牛的QQ资料
    单一登陆(Single Signon)问题
    Smart Client Case Study Source Code Download from MSDN China
    简历制作 | 论文资源 | 考试认证 | 招聘求职 | 文学艺术 | 外语学习
  • 原文地址:https://www.cnblogs.com/carterzhang/p/5326177.html
Copyright © 2020-2023  润新知