zoukankan      html  css  js  c++  java
  • jQuery的attr方法处理checkbox的问题

    现象

    使用了 jQuery 1.10 的版本,想实现 checkbox 的全部选中和全部取消选中,使用了 attr 的方法,如下:

    $(elem).attr(“checked”) 
    

    测试过程中发现,第一次从未选中状态变为选中,再从选中变为未选中,是可以的。但是第二次界面上就没有任何变化了,但是查看元素,发现 checked 属性实际上已经改变了。这是什么情况呢?

    原因

    看一下官方对这个函数的解释

    .attr()
    Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

    然后官方还特别注明了

    As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

    文档还特别对 attr() 和 prop() 进行了对比,总体来说 jQuery 1.6 版本之后,为了保证函数在不同环境下表现的一致性,建议对于获取 DOM 元素的固有属性,使用 prop() 方法,如果需要修改个性化(自定义)的属性字段,则需要使用 attr 方法。

    关于 checked 属性,还特别说了一下,我也不知道如何用汉字区分 attribute 和 property,还是摘抄下来吧。

    Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property

        if ( elem.checked )
        if ( $( elem ).prop( "checked" ) )
        if ( $( elem ).is( ":checked" ) )
    

    本文为作者原创,未经允许不得转载。如果您觉得本文对您有帮助,请随意打赏,您的支持将鼓励我继续创作。

    参考资料:
    1、jQuery attr
    2、jQuery prop
    3、W3C Forms

  • 相关阅读:
    搜索引擎常用技巧
    WinRaR去广告弹窗
    逆向破解之160个CrackMe —— 003
    逆向破解之160个CrackMe —— 002
    逆向破解之160个CrackMe —— 001(下)
    逆向破解之160个CrackMe —— 001(中)
    逆向破解之160个CrackMe —— 001(上)
    VMWare虚拟机无法开启,显示模块“Disk”启动失败解决办法
    uefi+gpt重装系统提示需要安装到gpt分区盘解决办法
    neg与sbb指令的结合使用
  • 原文地址:https://www.cnblogs.com/cocowool/p/7484857.html
Copyright © 2011-2022 走看看